Giter Site home page Giter Site logo

justinribeiro / lite-youtube Goto Github PK

View Code? Open in Web Editor NEW
832.0 9.0 63.0 362 KB

The fastest little YouTube web component on this side of the internet. The shadow dom web component version of Paul's lite-youtube-embed.

Home Page: https://www.npmjs.com/package/@justinribeiro/lite-youtube

License: MIT License

TypeScript 95.79% JavaScript 4.21%
web-component vanilla-webcomponent youtube

lite-youtube's Introduction

npm version min+gzip min+br

Statements Branches Functions Lines

<lite-youtube>

A web component that renders YouTube embeds faster. The ShadowDom web component version of Paul's lite-youtube-embed.

Features

  • No dependencies; it's just a vanilla web component.
  • It's fast yo.
  • It's Shadow Dom encapsulated!
  • It's responsive 16:9
  • It's accessible via keyboard and will set ARIA via the videotitle attribute
  • It's locale ready; you can set the videoplay to have a properly locale based label
  • Set the start attribute to start at a particular place in a video
  • You can set autoload to use Intersection Observer to load the iframe when scrolled into view.
  • Loads placeholder image as WebP with a Jpeg fallback
  • new in v1.1: Adds nocookie attr for use with use youtube-nocookie.com as iframe embed uri
  • new in v1.2: Adds playlistid for playlist loading interface support
  • new in v1.3: Adds loading=lazy to image placeholder for more perf with posterloading attr if you'd like to use eager
  • new in v1.4: Adds short attr for enabling experimental YouTube Shorts mobile interaction support. See (example video)[https://www.youtube.com/watch?v=aw7CRQTuRfo] for details.
  • new in v1.5: Adds support for nonce attribute via window.liteYouTubeNonce for CSP 2/3 support.

Install via package manager

This web component is built with ES modules in mind and is available on NPM:

To install, use your package manager of choice:

npm i @justinribeiro/lite-youtube
# or
yarn add @justinribeiro/lite-youtube

After install, import into your project:

import '@justinribeiro/lite-youtube';

Install with CDN

If you want the paste-and-go version, you can simply load it via CDN:

<script type="module" src="https://cdn.jsdelivr.net/npm/@justinribeiro/[email protected]/lite-youtube.js"></script>

Basic Usage

<lite-youtube videoid="guJLfqTFfIw"></lite-youtube>

Basic Usage with Fallback Link

A fallback appears in any of the following circumstances:

  1. Before the compontent is initialized
  2. When JS is disabled (like <noscript>)
  3. When JS fails or the lite-youtube script is not loaded/executed
  4. When the browser doesn't support web components
<lite-youtube videoid="guJLfqTFfIw">
  <a class="lite-youtube-fallback" href="https://www.youtube.com/watch?v=guJLfqTFfIw">Watch on YouTube: "Sample output of devtools-to-video cli tool"</a>
</lite-youtube>

Example CSS:

.lite-youtube-fallback {
	aspect-ratio: 16 / 9; /* matches YouTube player */
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	gap: 1em;
	padding: 1em;
	background-color: #000;
	color: #fff;
	text-decoration: none;
}

/* right-facing triangle "Play" icon */
.lite-youtube-fallback::before {
	display: block;
	content: '';
	border: solid transparent;
	border-width: 2em 0 2em 3em;
	border-left-color: red;
}

.lite-youtube-fallback:hover::before {
	border-left-color: #fff;
}

.lite-youtube-fallback:focus {
	outline: 2px solid red;
}

Playlist Usage

Setting the YouTube playlistid allows the playlist interface to load on interaction. Note, this still requires a videoid for to load a placeholder thumbnail as YouTube does not return a thumbnail for playlists in the API.

<lite-youtube
  videoid="VLrYOji75Vc"
  playlistid="PL-G5r6j4GptH5JTveoLTVqpp7w2oc27Q9"
></lite-youtube>

Add Video Title

<lite-youtube
  videotitle="This is a video title"
  videoid="guJLfqTFfIw"
></lite-youtube>

Update interface for Locale

<lite-youtube
  videoplay="Mirar"
  videotitle="Mis hijos se burlan de mi español"
  videoid="guJLfqTFfIw"
>
</lite-youtube>

Style It

Height and Width are responsive in the component.

<style>
  .styleIt {
    width: 400px;
    margin: auto;
  }
</style>
<div class="styleIt">
  <lite-youtube videoid="guJLfqTFfIw"></lite-youtube>
</div>

Enable YouTube Shorts interaction on mobile

See the example video of how this feature works for additional details.

<lite-youtube videoid="vMImN9gghao" short></lite-youtube>

AutoLoad with IntersectionObserver

Uses Intersection Observer if available to automatically load the YouTube iframe when scrolled into view.

<lite-youtube videoid="guJLfqTFfIw" autoload> </lite-youtube>

Set a video start time

<!-- Start at 5 seconds -->
<lite-youtube videoid="guJLfqTFfIw" videoStartAt="5"></lite-youtube>

Fine tune the poster quality for a video

<lite-youtube
  videoid="guJLfqTFfIw"
  posterquality="maxresdefault"
></lite-youtube>

YouTube QueryParams

Use any YouTube Embedded Players and Player Parameters you like.

Note: the exception to this rule is the autoplay param; because of the nature of the performance loading and the inconsistency of usage, that parameter generally does not work. See this comment for details.

<lite-youtube videoid="guJLfqTFfIw" params="controls=0&enablejsapi=1">
</lite-youtube>

Attributes

The web component allows certain attributes to be give a little additional flexibility.

Name Description Default
videoid The YouTube videoid ``
playlistid The YouTube playlistid; requires a videoid for thumbnail ``
videotitle The title of the video Video
videoplay The title of the play button (for translation) Play
videoStartAt Set the point at which the video should start, in seconds 0
posterquality Set thumbnail poster quality (maxresdefault, sddefault, mqdefault, hqdefault) hqdefault
posterloading Set img lazy load attr loading for poster image lazy
nocookie Use youtube-nocookie.com as iframe embed uri false
autoload Use Intersection Observer to load iframe when scrolled into view false
short Show 9:16 YouTube Shorts-style interaction on mobile devices false
params Set YouTube query parameters ``

Events

The web component fires events to give the ability understand important lifecycle.

Event Name Description Returns
liteYoutubeIframeLoaded When the iframe is loaded, allowing us of JS API detail: { videoId: this.videoId }

lite-youtube's People

Contributors

abdonrd avatar abraham avatar anatolykopyl avatar dependabot[bot] avatar justinribeiro avatar mrwweb avatar neilitalia avatar neon-dev avatar ridem avatar ru-ka avatar slightlyoff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lite-youtube's Issues

Not working in nuxt 2

We are using version 0.9.1 and it works fine, but we're having trouble with youtube-nocookie and the hell of un-used javascript it brings. After upgrading to v1.5.0, I'm getting this error in Nuxt 2 project:

/node_modules/@justinribeiro/lite-youtube/lite-youtube.js                        friendly-errors 16:46:05

Module parse failed: Unexpected token (232:23)                                                         friendly-errors 16:46:05
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|         this.domRefImg.fallback.src = posterUrlJpeg;
|         this.domRefImg.fallback.setAttribute('aria-label', `${this.videoPlay}: ${this.videoTitle}`);
>         this.domRefImg?.fallback?.setAttribute('alt', `${this.videoPlay}: ${this.videoTitle}`);
|     }
|     initIntersectionObserver() {

And we're just using it like this:

<lite-youtube
    v-if="provider === 'youtube'"
    :videoid="embedId"
></lite-youtube>

<noscript>
    <iframe
    loading="lazy"
    height="315"
    :src="iframeSrc"
    title="video player"
    frameborder="0"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
    ></iframe>
</noscript>

Probable bug wrt capitalization

I'm guessing that there's some bug here:

case 'videoid':
case 'playlistid':
case 'videoTitle':
case 'videoPlay': {

Maybe the last two should be lowercased? And if so, then probably also the attribute name in the getter/setter should be lowercased as well?

Related, and I'm not sure about it since I don't have experience with it, but maybe they should both be included in observedAttributes?

Benchmark?

Hey, i was just wondering - is it faster than the original youtube-lite-embed?
If so, is it observable in some synthetic benchmarks?

Ive seen some screenshots from chrome performance tab in Paul Irish repo, and question popped up - why use shadow dom version instead of the customelement? Was it just an excercise, or there are some real benefits?

enablejsapi param not working

I just switched to lite-youtube from the original YouTube embed once I got all my params working with the original.

I noticed that after the switch Google Analytics stopped reporting on any video events at all. All of the other params I've changed have worked like: cc_lang_pref, color, hl, playsinline, rel.

Any ideas what could be going on here? I absolutely love this package and want to use it but getting the events is critical in my case.

Mobile double-tap and autoload

I run a little hobby project and the core functionality is displaying specific YouTube videos. 85% of my users are mobile, the YT video is above the fold and 100% of visitors play the YT video.
I initially implemented your fantastic module as Pagespeed Insights tagged the YT iframe as an area of improvement and a facade would improve loading times etc. and therefor hopefully ranking.
The issue now is that on mobile, without autoload activated, it requires two tabs to play the video (as mentioned in #23 and #30). If I activate autoload, the Intersection Observer will basically instantly trigger as the video is above the fold. This does "work" but I wonder how much of an actual improvement this is over the just embedding the iframe.

Do you have any opinion on this scenario? Will adding lite-youtube in this case actually improve things or does it not make any sense in this case?

An example of a page is: https://www.cocktailexplorer.co/cocktails/rebujito/behind-the-bar/

Make poster image quality configurable

It looks like hqdefault is used by default for the poster image. We need to change this to maxresdefault since hq is just too low res for our needs. Would it be possible to add this as a configurable option?

Usage in Typescript?

I'm having trouble using this component in a Gatsby Typescript product.

The web-component is not recognized as a valid JSX element. Do you have any guidance on how we may overcome this issue?

I see that the source code is written in typescript, with a global declaration at the bottom. But perhaps this isn't being picked up by my Typescript settings?

Here is the specific error: Property 'lite-youtube' does not exist on type 'JSX.IntrinsicElements'.

Remove `#frame::before`?

It took me a while to realize that the top shadow effect is coming from here and not from youtube...

Initially I thought about adding another attribute to specify the gradient, or the whole ::before etc -- but then I remembered this from CONTRIBUTING.md:

Anything that adds bloat or perf loss won't be accepted [...]

So for myself, I just nuked it, but following the same motto, it seems fitting to drop it -- if anyone wants to see a shadow, they can add one themselves, no?

Add a nonce for CSP policy enforcement

Is there a way I can add a nonce to the short-code that would work for CSP?

                                <lite-youtube
                                    videoid="abc123"
                                    videotitle="Video of cats"
                                    autoload
                                    nonce="{{ csp_nonce() }}"
                                ></lite-youtube>
                                ```
Adding a nonce didn't work.

Best method to avoid Cumulative Layout Shift?

Hey, love the facade, definitely helps to decrease the Time to Interactive and Total Blocking Time on the page.

We are experiencing a large amount of Cumulative Layout Shift since implementing lite-youtube, and was wondering if any of the contributors or users of the component have solved this. The native iframe didn't seem to have this issue.

Is there a way that I can get the height and width of the video earlier, or apply styles to the component to avoid this?

Autoplay

I tried to add params="autoplay=1" to allow auto play (also autoload to start to play once it is on screen)

however, it does not work. It's because the plugin automatically includes autoplay=0 on all urls.

solution
either:
1* not include autoplay=0 on video url
2* flag this behaviour

Issue with HDR Videos Being Displayed using lite-youtube

Hi there,

We have used the lite-youtube code for some time now. All works wonderfully.

However, we have an issue when embedding videos available in HDR

The videos are completely washed out and much too bright.

Example of lite-youtube embed with HDR video:
Screen Shot 2022-02-09 at 21 58 25

What the actual video should look like (from YouTube):

Screen Shot 2022-02-09 at 21 59 32

We tested with a standard YouTube IFRAME embed of the same video and all works just fine with HDR - it displays correctly.

We were testing on Chrome (latest stable).

Doesn't work well when aspect ratio is different from 16:9

I have a page with a few videos that have a weird non-16/9 aspect ratio. The result renders that inside of a 16/9 iframe which makes it look bad. I just blindly grepped the code for 16 / 9 and changed it which looks like it makes it work as intended.

Update to latest version

Looks like there's been several new versions of lite-youtube-embed. Are there any plans to bump this repo to the latest version?

Use official YouTube logo

Would it be possible to use the official YouTube logo for the previews?

By default this is how it looks:

image

I'm currently using this with vanilla js and as a quick hack, I took some styling from Paul Irish's lite-youtube and appended these styles into the shadow dom

const liteYoutube = document.querySelector("lite-youtube")
styleEmbed(liteYoutube)

function styleEmbed(embed) {
  const style = document.createElement("style")
  style.textContent = /*css*/`
    #playButton {
      display: block;
      width: 68px;
      height: 48px;
      position: absolute;
      cursor: pointer;
      transform: translate3d(-50%, -50%, 0);
      top: 50%;
      left: 50%;
      z-index: 1;
      background-color: transparent;
      background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 68 48"><path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55c-2.93.78-4.63 3.26-5.42 6.19C.06 13.05 0 24 0 24s.06 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C67.94 34.95 68 24 68 24s-.06-10.95-1.48-16.26z" fill="red"/><path d="M45 24 27 14v20" fill="white"/></svg>');
      filter: grayscale(100%);
      transition: filter .1s cubic-bezier(0, 0, 0.2, 1);
      border: none;
      border-radius: inherit;
    }
    #frame:hover > #playButton,
    lite-youtube #playButton:focus {
      background-color: transparent;
      filter: none;
      border-radius: inherit;
    }
  `
  embed.shadowRoot.appendChild(style)
}

Resulting in a little bit of a nicer preview

image

I think it would look great like this out-of-the-box. I could start a PR if this sounds good.

Custom poster image

Hi,

Thanks for your work on this!

I wondered if you'd consider having a poster image attribute so people could choose to override the YouTube-generated poster images?

Many thanks.

Add method for IFRAME postmessage

With lite-youtube we out of control.
Please add proxy method for send iframe postmessage

Original postmessage
iframe.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');

Lite postmessage (something like this)
[lite-youtube.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');

p.s. listener from iframe would be nice, too.

params function not working

Hey guys,

Been implementing this wonderful lite-youtube solution on my clients site to much success. Recently when asked to add the rel=0 param to the videos I followed the instructions listed and nothing happens. I also tried a load of other parameters to no success either. Could anyone assist me in getting the params to work :)

<lite-youtube videoid="arygCLXYB7Y" params="rel=0"> </lite-youtube>

Poster image still gets lazy-loaded when setting posterloading to eager

<lite-youtube videoid="{{ video }}" posterloading="eager"></lite-youtube>

Results in:

<img id="fallbackPlaceholder" referrerpolicy="origin" loading="lazy" src="..." aria-label="..." alt="...">

I'm using v1.4.0


There seems to be a hard-coded loading="lazy" when the shadow dom gets set up (I guess this is just the default setup):
/blob/main/lite-youtube.ts#L210

Maybe the "fallback" reference isn't working here:
/blob/main/lite-youtube.ts#L323

Not working in Firefox

I have a trouble with Firefox not showing anything
I'm using FF 91 and 0.9.1 of the lite youtube

If I turn of position: absolute; for #frame, #fallbackPlaceholder, iframe then image is shown but video is being loaded under the picture.

CSS issue with more than one embed

In the youtube lite css and html is referenced an "#frame" ID.

This can create issues with more videos on the same page.
It could be better to use a CSS class like ".yt-lite-frame"

Then for the placeholder placement it's better to use left: 0 on the ".yt-lite-frame" (ex #frame).

Module parse failed: Unexpected token ...

Hi, i have this issue, maybe you can help ?
Thanks!

ERROR in ./node_modules/@justinribeiro/lite-youtube/lite-youtube.js 224:23
Module parse failed: Unexpected token (224:23)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|         this.domRefImg.fallback.src = posterUrlJpeg;
|         this.domRefImg.fallback.setAttribute('aria-label', `${this.videoPlay}: ${this.videoTitle}`);
>         this.domRefImg?.fallback?.setAttribute('alt', `${this.videoPlay}: ${this.videoTitle}`);
|     }
|     initIntersectionObserver() {
 @ ./src/js/main.js 3:0-37
 @ ./src/index.js
package.json :

{
  "name": "nesto-2022",
  "version": "2.0.0",
  "description": "Custom WordPress Theme",
  "main": "index.js",
  "author": "Strong Developpement",
  "license": "UNLICENSED",
  "private": true,
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/runtime": "^7.9.2",
    "autoprefixer": "^9.7.5",
    "babel-loader": "^8.1.0",
    "babel-plugin-import": "^1.13.3",
    "babel-plugin-transform-remove-console": "^6.9.4",
    "browser-sync": "^2.26.7",
    "browser-sync-webpack-plugin": "^2.2.2",
    "clean-webpack-plugin": "^3.0.0",
    "compression-webpack-plugin": "6.1.1",
    "core-js": "^3.8.0",
    "css-loader": "^3.4.2",
    "file-loader": "^6.0.0",
    "glob": "^7.1.7",
    "html-loader": "^1.1.0",
    "image-minimizer-webpack-plugin": "^1.0.0",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-jpegtran": "^6.0.0",
    "imagemin-optipng": "^8.0.0",
    "imagemin-pngquant": "^8.0.0",
    "imagemin-svgo": "^7.1.0",
    "imagemin-webp": "^6.0.0",
    "imagemin-webpack-plugin": "^2.4.2",
    "mini-css-extract-plugin": "^0.9.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "postcss-loader": "^3.0.0",
    "sass": "^1.26.3",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "terser-webpack-plugin": "^2.3.5",
    "url-loader": "^4.0.0",
    "webpack": "^4.42.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^3.10.3",
    "webpack-notifier": "^1.8.0"
  },
  "scripts": {
    "start": "yarn dev",
    "dev": "webpack --mode development --progress --watch",
    "build": "webpack --mode production"
  },
  "dependencies": {
    "@justinribeiro/lite-youtube": "^1.3.1"
  },
  "browserslist": [
    "defaults"
  ]
}

webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const ImageminPlugin = require('image-minimizer-webpack-plugin');
const autoprefixer = require('autoprefixer');
const WebpackNotifierPlugin = require('webpack-notifier');

module.exports = (env, argv) => {
  let devmode = argv.mode === 'development';
  let babelPlugins = [
    '@babel/plugin-transform-runtime',
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-class-properties'
  ];

  if(!devmode) babelPlugins.push(['transform-remove-console', { 'exclude': [ 'error', 'warn', 'info' ] }]);

  return {
    mode: argv.mode,
    entry: './src',
    output: {
      filename: '[name].js',
      chunkFilename: `[name].chunk.js`,
      path: path.resolve(__dirname, 'dist'),
      publicPath : '/wp-content/themes/nesto2022/dist/'
    },
    devtool: devmode ? 'source-map' : false,
    performance : {
      hints : devmode ? false : "warning"
    },        
    plugins: [
      new CleanWebpackPlugin(),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[name].chunk.css'
      }),
      new ImageminPlugin({
        minimizerOptions: {
          plugins: [
            ['gifsicle', { interlaced: true }],
            ['jpegtran', { progressive: true }],
            ['optipng', { optimizationLevel: 3 }],
            [
              'svgo',
              {
                plugins: [
                  { optimizationLevel: 3 },
                  { progessive: true },
                  { interlaced: true },
                  { removeViewBox: false },
                  { removeUselessStrokeAndFill: true },
                  { cleanupIDs: true },
                  { minifyStyles: true },
                  { inlineStyles: true }
                ]
              }
            ]
          ]
        }
      }),
      new BrowserSyncPlugin( {
        open: 'external',
        host: 'devnesto.com',
        proxy: 'devnesto.com',
        port: 3000,
        files: [
          'src/js/',
          'images/**/*',
          './**/*.css',
          './**/*.php'
        ],
        },
        // plugin options
        {
          // prevent BrowserSync from reloading the page
          // and let Webpack Dev Server take care of this
          reload: false,
          injectCss: true
        }
      ),
      new WebpackNotifierPlugin(),
    ],
    module: {
      rules: [ 
        {
          test: /\.js$/,
          exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: [
                [ '@babel/preset-env', {
                    useBuiltIns: 'entry',
                    corejs: 3,
                    debug: devmode
                } ]
              ],
              'plugins': babelPlugins
            }
          } 
        },
        {
          test: /\.(sa|sc|c)ss$/,      
          use: [
              MiniCssExtractPlugin.loader,
              'css-loader', {
                loader: 'postcss-loader',
                options: {
                  ident: 'postcss',
                  plugins: () => [autoprefixer()]
                }
              },
              'sass-loader'
          ]
        },
        {
          test: /\.(jpe?g|png|gif|svg)$/i,
          exclude: /fonts/,
          use: [
            {
              loader: 'url-loader',
              options: {
                  limit: 5120,
                  name: 'images/[name].[ext]'
              }  
            }
          ]
        },
        {
          test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
          exclude: /images/,
          use: [
            {
              loader: 'url-loader',
              options: {
                  limit: 5120,
                  name: 'fonts/[name].[ext]'
              }  
            }
          ]
        }
      ]
    },
    optimization: {
      minimizer: [
        new TerserPlugin(),
        new OptimizeCSSAssetsPlugin()
      ]
    }
  }
};

Use of youtube-nocookie for videos

Hey, this is a nice little component, thanks very much.

I noticed that on Paul's original, he used youtube-nocookie.com to embed the videos, but couldn't see that in this code. Are there issues using the nocookie.com domain maybe (we've experienced a few oddities with it), or what was the reasoning?

Thanks!

Webpack Error

ModuleParseError: Module parse failed: Unexpected token (224:23)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| this.domRefImg.fallback.src = posterUrlJpeg;
| this.domRefImg.fallback.setAttribute('aria-label', ${this.videoPlay}: ${this.videoTitle});
this.domRefImg?.fallback?.setAttribute('alt', ${this.videoPlay}: ${this.videoTitle});
| }
| initIntersectionObserver() {

relevant snippet of webpack config:

{
test: /.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
},

Anything missing here? Thanks!

errors in Next.js due to export

While running yarn dev I am getting the below error. Installed the package via yarn.

error - /Users/konrad/Projects/go4ngo-landing-page/node_modules/@justinribeiro/lite-youtube/lite-youtube.js:1
export class LiteYTEmbed extends HTMLElement {
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1084:15)
    at Module._compile (node:internal/modules/cjs/loader:1119:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Module.require (node:internal/modules/cjs/loader:1057:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.@justinribeiro/lite-youtube (/Users/konrad/Projects/go4ngo-landing-page/.next/server/pages/index.js:504:18)
    at __webpack_require__ (/Users/konrad/Projects/go4ngo-landing-page/.next/server/webpack-runtime.js:33:42) {
  page: '/'
}

Google indexing errors

Hey, I’m a huge fan of this project, which saves a ton of loading time on my site when it comes to embeds. However, I noticed that the script created an indexing problem that Google Search Console pointed out:

Screen Shot 2023-04-03 at 4 23 14 PM

Screen Shot 2023-04-03 at 4 23 29 PM

Essentially, it is no longer tagging these videos as videos.

I don’t know if there is an easy solution to this, but it appears that the use of this script is creating unintentional side effects that are proving potentially damaging from an SEO standpoint. Any thoughts on a potential common ground here?

Package should specify that it's a module

When using this package with Vite, I'm getting the following error:

@justinribeiro/lite-youtube doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.

See source

Given the package is built as an ES module, I'm suggesting adding "type": "module" to package.json

YouTube Clips

Is there a way to add the ability to use this with YouTube Clips?

Lazy or Eager loading

Is it possible to introduce a new parameter to decide if the preview image should be loaded with loading=lazy or loading=eager?

Webp images missing

There are a multitude of videos that do not have the webp thumbnail.

Paul Irish even mentions the unreliability in his code:

    * Lo, the youtube placeholder image!  (aka the thumbnail, poster image, etc)
    * There is much internet debate on the reliability of thumbnail URLs. Weak consensus is that you
    * cannot rely on anything and have to use the YouTube Data API.

https://github.com/paulirish/lite-youtube-embed/blob/a927d63781883088c185cb69a0baade52732ab3e/src/lite-yt-embed.js#L22

I have not spent a lot of time with this, but I think there's no good and simple solution for this that includes webp. The easy and pragmatic solution is probably to simply forgo the webp version.

Add option to mute

Is it possible to add a param for muted on play?

<lite-youtube videoid="IJq_8gbiVBg" start="35" mute="1" autoload>

Jpeg fallback not used when webp is missing

When the webp image is missing for a video, youtube serves their own fallback image in it's place. So, the webp-image is never really missing from the browsers point of view, which means that the JPG fallback is never used.

In my project this happens with quite a lot of videos. Any custom workarounds I could do to fix it? Perhaps there could be an option to disable webp?

Example, videoid FqpiXeG1eJg :

https://i.ytimg.com/vi_webp/FqpiXeG1eJg/hqdefault.webp // renders youtubes fallback image
https://i.ytimg.com/vi/FqpiXeG1eJg/hqdefault.jpg // renders the correct image, but is never used

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.