Better page load performance when loading multiple embedded Youtube videos?

Tom picture Tom · Sep 29, 2011 · Viewed 14.5k times · Source

I have a page which displays multiple (usually 10) embedded videos. The videos use the new IFRAME embed code of youtube and apparently for every IFRAME there is a separate request when loading the page. Is there a way to defer loading the videos after the rest of the page is loaded, so they don't slow down page loading that much?

Answer

futtta picture futtta · Sep 29, 2011

Well, I wrote a javascript thingy (called "LYTE") that will create a "dummy player" (which looks & feels like a normal YouTube embed) for every div with a specific class ("lyte") and id with the YouTube-id. Only when clicking the "dummy" player, the actual YouTube iframe is loaded and it indeed has an important impact of the performance of pages that embed YouTube videos. You can see it in action on my blog.

LYTE is currently not really available standalone, only as part of WP-YouTube-Lyte, the WordPress plugin I wrote, but with minimal changes you should be able to extract all relevant code from the plugin.

You basically have to create something like this in your HTML;

<div class="lyte" id="7nuiOe8M6bw" style="width:640px;height:385px;">
<script type="text/javascript"><!-- 
var nT='newtube-';var bU='http://static.blog.futtta.be/wp-content/plugins/wp-youtube-lyte/lyte/';
var d=document;if(d.addEventListener){d.addEventListener('DOMContentLoaded', insert, false)}else{window.onload=insert}
function insert(){if(!d.getElementById('lytescr')){lytescr=d.createElement('script');lytescr.async=true;lytescr.id='lytescr';lytescr.src='http://static.blog.futtta.be/wp-content/plugins/wp-youtube-lyte/lyte/lyte-min.js';h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(lytescr, h)}}; 
 --></script></div>

This block will load lyte-min.js, which will fill the div with all graphical elements of the dummy player (image, play button, control bar, title) and will add an eventlistener to the div that will trigger the replacement of the div with the real embedded player when clicked.

You can find the plugin here and look at the code here (wp-youtube-lyte.php creates the div, lyte/lyte.js is the actual javascript ... thingy).