Skip to main content

A More Efficient Method for Embedding YouTube Videos

When you embed any YouTube video on your website using standardIFRAME tags, you’ll be surprised to know how much extra weight that YouTube video will add to your page. The web page has to download ~0.5 MB of extra resources (CSS, JavaScript and images) for rendering the YouTube video player and the files will download even if the visitor on your website has chosen not to watch the embedded YouTube video.

YouTube Player - Waterfall

The embedded video is making your page heavy and the visitor’s browser will also need to make multiple HTTP requests to render the video player. This increases the overall loading time of your page and thus affects the page speed score. The other drawback with the default YouTube embed code is that it isn’tresponsive. If people view your website on a mobile phone, the video player would not resize itself accordingly.

Load YouTube Video Player On-Demand


Google Plus uses a clever workaround to reduce the time it takes to initially load the YouTube video player and we can incorporate a similar approach approach for our websites as well.

Instead of embedding the full Youtube video player, Google+ displays just the thumbnail images of a YouTube video and a “play” icon is placed over the video so that it looks like a video player. The following video is embedded using the same technique:







When the user hits the play button, the video thumbnail is replaced with the standard YouTube video player with autoplay set to 1 so it plays the video instantly. The extra player-specific resources are thus loaded only when the user has decided to play the embedded video and not otherwise.

The regular embed code for YouTube looks something like this. You specify the height of the player (in pixels), the width and the unique ID of the YouTube video.

  1. <iframe width="320" height="180"

  2. src="http://www.youtube.com/embed/LcIytqkbdlo">

  3. </iframe>


Embed YouTube Videos Responsively without Increasing Load Time


The on-demand embed code for YouTube is slightly different since we are now embedding the video responsively and also because the IFRAME embed code is added only then user clicks the play button.

Copy-paste the following snippet anywhere in your web page where you would like the video to appear. Remember to replace VIDEOID with the actual ID of the YouTube video. The CSS and JavaScript codes are added to the template separately. Also, there’s no need to add the height and width parameter since the video will automatically occupy the width of the parent while the height is auto-calculated.

  1. <div class="youtube-container">

  2. <div class="youtube-player" data-id="VIDEOID"></div>

  3. </div>


You can copy-paste multiple blocks on the same page incase you need to embed multiple videos on the same page. The code will stay the same except that you need to change the VIDEOID for each of the blocks.

The JavaScript


The JavaScript function will scan your pages for embedded YouTube videos. If found, it will add the corresponding thumbnail image and also add the onclick event listener that will do the actual magic – replace the image with the actual YouTube video in autoplay mode.

  1. <script>

  2. (function() {

  3. var v = document.getElementsByClassName("youtube-player");

  4. for (var n = 0; n < v.length; n++) {

  5. var p = document.createElement("div");

  6. p.innerHTML = labnolThumb(v[n].dataset.id);

  7. p.onclick = labnolIframe;

  8. v[n].appendChild(p);

  9. }

  10. })();

  11.  

  12. function labnolThumb(id) {

  13. return '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + id + '/hqdefault.jpg"><div class="play-button"></div>';

  14. }

  15.  

  16. function labnolIframe() {

  17. var iframe = document.createElement("iframe");

  18. iframe.setAttribute("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");

  19. iframe.setAttribute("frameborder", "0");

  20. iframe.setAttribute("id", "youtube-iframe");

  21. this.parentNode.replaceChild(iframe, this);

  22. }

  23. </script>


The CSS


Open the CSS file of your website and paste the following snippet. If you don’t have a separate CSS file, you can also place it before the closing head tag of your web template.


  1. <style>

  2. .youtube-container { display: block; margin: 20px auto; width: 100%; max-width: 600px; }

  3. .youtube-player { display: block; width: 100%; /* assuming that the video has a 16:9 ratio */ padding-bottom: 56.25%; overflow: hidden; position: relative; width: 100%; height: 100%; cursor: hand; cursor: pointer; display: block; }

  4. img.youtube-thumb { bottom: 0; display: block; left: 0; margin: auto; max-width: 100%; width: 100%; position: absolute; right: 0; top: 0; height: auto }

  5. div.play-button { height: 72px; width: 72px; left: 50%; top: 50%; margin-left: -36px; margin-top: -36px; position: absolute; background: url("http://i.imgur.com/TxzC70f.png") no-repeat; }

  6. #youtube-iframe { width: 100%; height: 100%; position: absolute; top: 0; left: 0; }

  7. </style>


This method will reduce the size of your webpages by 300-400 KB while making your site mobile friendly. You may refer to the annotated code to understanding how on-demand embedding works.

 

Comments

Post a Comment

If you have anything in mind, please let me know!

Popular posts from this blog

7 Data Recovery 2.3.0 Enterprise Serial Keys are Here ! Comprehensive Data Recovery Software for All Your Needs

Recover Your Data Efficiently and Effectively 7 Data Recovery is a complete and capable data recovery software designed to rescue your files under almost any conditions. Whether you've accidentally deleted files, have a damaged or formatted hard drive, or lost data from mobile devices, 7 Data Recovery has you covered. Main Features Accidentally Deleted Files Recovery:  Quickly recover files that have been mistakenly deleted. Complete Recovery from Local & External Drives:  Restore data from both internal and external storage devices. Recover Data from Lost and Deleted Partitions:  Retrieve data from partitions that have been lost or deleted. Recovery of Photos, Images, Videos, and Audio:  Recover various media files from different sources. Mobile Phone Recovery on Windows:  Extract lost data from your mobile devices using a Windows PC. Memory Card Recovery:  Recover files from memory cards used in cameras, phones, and other devices Download and Registra...

Revo Uninstaller Pro 3.0.8 (Latest) Crack is Here ! The Ultimate Solution for Software Removal

Revo Uninstaller Pro helps you effortlessly uninstall software and remove unwanted programs installed on your computer! Even if you face issues uninstalling programs via the default “Windows Programs and Features (Add or Remove Programs)” control panel applet, Revo Uninstaller Pro is your go-to solution. Why Choose Revo Uninstaller Pro? Revo Uninstaller Pro is a faster and more powerful alternative to the “Windows Programs and Features (Add or Remove Programs)” applet! It comes packed with powerful features to ensure complete uninstallation and removal of programs. Key Features of Revo Uninstaller Pro Extended Scanning for Leftovers: Advanced algorithms ensure no remnants are left behind. Real-Time System Monitoring: Track system changes during program installation. Forced Uninstall: Remove remnants of already uninstalled programs. Quick/Multiple Uninstall: Quickly uninstall one or multiple programs in a row. Logs Database Usage: Integrate with a database of installation logs for a be...

Auslogics BoostSpeed Premium 7.3.1.0 Serial Keys are Here ! [Latest]

Auslogics BoostSpeed 7 AusLogics BoostSpeed : the ideal solution to keep your PC running faster, cleaner and error-free. This powerful optimization suite will boost Internet connections, tweak Windows to its peak performance, clean registry and block annoying ads. It’s a great way to keep your computer clean and optimized. Modify Windows settings, file system and services to greatly increase system performance. Increase startup and shutdown speed, disable annoying CD autorun and error reporting features. BoostSpeed will keep monitoring your system for possible optimizations and let you know if such optimizations are possible. You can also run the System Optimization Wizard to periodically optimize your PC. Speed Up PC With BoostSpeed Modify Windows settings, file system and services to greatly increase system performance. Increase startup and shutdown speed, disable annoying CD autorun and error reporting features. BoostSpeed will keep monitoring your...