Note that there are some explanatory texts on larger screens.

plurals
  1. POFirst attempt at lazy loading (deferring the load of embedded YouTube videos) - how can I do this more gracefully?
    text
    copied!<p>Yesterday I decided to improve the way my website loads YouTube videos by only embedding them when a user requests them. Sometimes a page could have as many as 30 videos on, and this would take a long time to load.</p> <p>This is the first time I've attempted a "lazy loading" method of anything, and I figured it would be well worth asking:</p> <p><strong>What can I do to improve on this?</strong></p> <p><strong>How can I make it a bit more graceful?</strong></p> <p><strong>Does this completely miss the point of deferred loading?</strong></p> <p><a href="http://jsfiddle.net/n5v6A/8/" rel="nofollow">JSFiddle</a>.</p> <p>Ignore the styling as that's irrelevant here.</p> <hr> <p>The way this works is by first placing an anchor on the page containing the video's ID:</p> <pre><code>&lt;a href="#" data-video="FzRH3iTQPrk" class="youtube-video"&gt; </code></pre> <p>The jQuery behind then loops through every <code>a.youtube-video</code> and creates a transparent span with the video's thumbnail as its background:</p> <pre><code>$('a.youtube-video').each(function() { var videoId = $(this).attr('data-video'); var videoThumbnail = "http://img.youtube.com/vi/" + videoId + "/0.jpg"; var videoBackground = $('&lt;span class="youtube-thumbnail"&gt;&lt;/span&gt;'); videoBackground.css({ background:"#fff url('"+videoThumbnail+"') no-repeat" }) ... </code></pre> <p>It then modifies the styling of the anchor tag (this is done here to prevent affecting browsers with JavaScript disabled):</p> <pre><code> $(this).css({ height:315, width:460, position:"relative", display:"block", textAlign:"center", color:"#fff", fontSize:26 }); </code></pre> <p>It then finishes up the loop by adding the span to the anchor:</p> <pre><code> $(this).text('Click to load video'); $(this).append(videoBackground); }); </code></pre> <p>The loading of the embedded YouTube video object occurs on the anchor click:</p> <pre><code>$('a.youtube-video').click(function(e) { e.preventDefault(); var videoId = $(this).attr('data-video'); var videoThumbnail = "http://img.youtube.com/vi/" + videoId + "/0.jpg"; var videoEmbed = $('&lt;object&gt; ... &lt;/object&gt;'); ... </code></pre> <p>This finishes up by adding the embed code to the anchor's parent and removing the anchor:</p> <pre><code> $(this).parent().append(videoEmbed); $(this).hide(); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload