Lazy Load Embed YouTube Player – youtube-iframe

Category: Javascript , Loading | February 16, 2022
Author:emorozov28
Views Total:645 views
Official Page:Go to website
Last Update:February 16, 2022
License:MIT

Preview:

Lazy Load Embed YouTube Player – youtube-iframe

Description:

If you have a ton of videos on your site, you’re probably familiar with lazy loading.

Using this library you can easily add Lazy Loading functionality to your Youtube videos embedded in your document.

It does so by displaying the Youtube video thumbnail on page init, waiting until users click on the Play button, and then loading the video. This means that content below the player is not loaded until after it has been clicked, which will result in faster page loading times overall.

How to use it:

1. Load the necessary JavaScript and CSS files from the dist folder.

<script defer src="index.js"></script>
<link href="index.css" rel="stylesheet" />

2. Or import the youtube-iframe as a module.

import LazyLoadYouTube from 'lazy-load-youtube';
import 'lazy-load-youtube/index.css';

3. Create a placeholder for your Youtube video. Don’t forget to replace the Video Link (OR Video ID) in the data-video-link attribute:

<div class="video__wrap">
  <div class="video__item js-video-item" data-video-link="VIDEO LINK OR ID">
    <span class="video__caption js-video-caption">Video Cpation</span>
    <button class="video__play js-video-play"></button>
  </div>
</div>

4. Initialize the LazyLoadYouTube.

document.addEventListener('DOMContentLoaded', function() {
  new LazyLoadYouTube('.js-video-item');
});

5. Customize the play button.

new LazyLoadYouTube('.js-video-item',{
    button: '<svg>...</svg>'
    buttonLabel: 'Play Now'
});

6. Set the quality of the VIDEO thumbnail.

  • hqdefault
  • mqdefault
  • sddefault
  • maxresdefault
new LazyLoadYouTube('.js-video-item',{
    imageBg: true,
    qualityBg: 'hqdefault',
});

7. Enable a button to pause all videos.

<button class="js-video-stop">
  Stop Videos
</button>
lazyLoadYouTube.stopVideo();

You Might Be Interested In:


Leave a Reply