A More Efficient Embedding Method for YouTube Videos

A More Efficient Embedding Method for YouTube Videos
by Janeth Kent Date: 11-04-2013

When you embed any YouTube video on a website using standard IFRAME tags, you’ll be surprised to know how many extra pounds that video adds to your page.

The web page has to download additional ~400 kB of resources (CSS, JavaSript and Image files) for rendering the video player alone and these extra resources will download even if the site visitor has chosen not to watch the embedded YouTube video.

This can be a problem for two reasons. Once, we are indirectly adding extra weight (nearly 0.4 MB) to our pages and second, the visitor’s browser has to make multiple HTTP requests to render the video player. Both these factors will increase the overall loading time of your page and can possibly affect the page speed score as well.

Solution: Load the 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 easily incorporate that approach on our sites as well.

Instead of embedding the full Youtube video player, Google+ only displays the thumbnail of a YouTube video and then overlays a play icon over the video so the image resembles a video player. Take a look at this sample video embedded below (or on Google Plus).

When the user hits the play button, the image thumbnail gets replaced with the standard video player. Thus, the extra player-specific resources are loaded only when the user has decided to play the embedded video and not otherwise.

Code: Embed YouTube Videos without Increasing Load Time

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

  1. <iframe width="320" height="180"
  2.  src="http://www.youtube.com/embed/LcIytqkbdlo">
  3. </iframe>

And here’s the corresponding on-demand code for YouTube. You have to replace the height, width and the Youtube ID in the code above and then copy-paste it anywhere in your web template.

<div class="youtube" id="LcIytqkbdlo" style="width: 320px; height: 180px;"></div>
<script src="https://labnol.googlecode.com/files/youtube.js"></script>

This little change will reduce the size of your page by at least 300 KB while improving user experience. You may refer to the annotated code to learn how on-demand embedding works.

[*] If you have a high-traffic site, please make a copy of the minified youtube.js file from googlecode.com and host it on your own server.


by Janeth Kent Date: 11-04-2013 hits : 3714  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.