Yesterday, I decided to improve the way my site is uploaded to YouTube by adding them only when the user requests them. Sometimes a page can have up to 30 videos, and it takes a long time to load.
This is the first time I have tried using the "lazy loading" method, and I thought it would be nice to ask:
What can I do to improve this?
How can I make it more elegant?
Has this completely missed the point of delayed loading?
JSFiddle .
Ignore the style that doesn't matter here.
How it works by first placing the anchor on the page containing the video ID:
<a href="#" data-video="FzRH3iTQPrk" class="youtube-video">
jQuery a.youtube-video :
$('a.youtube-video').each(function() {
var videoId = $(this).attr('data-video');
var videoThumbnail = "http://img.youtube.com/vi/" + videoId + "/0.jpg";
var videoBackground = $('<span class="youtube-thumbnail"></span>');
videoBackground.css({
background:"#fff url('"+videoThumbnail+"') no-repeat"
})
...
( , JavaScript):
$(this).css({
height:315,
width:460,
position:"relative",
display:"block",
textAlign:"center",
color:"#fff",
fontSize:26
});
, :
$(this).text('Click to load video');
$(this).append(videoBackground);
});
YouTube :
$('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 = $('<object> ... </object>');
...
:
$(this).parent().append(videoEmbed);
$(this).hide();
});