My website loads slow because of too many embedded videos. I'm seen where there is an image (overtop of where the video is embedded) and you click it, at which point, the embedded video is loaded. Could anyone give me some help figuring out how to do this? Maybe once you hover over the image the youtube embed if loaded? Thanks so much!

有帮助吗?

解决方案

Just use jQuery to insert the embed code after the user clicks on the image:

Just sample code: HTML

<div id="video" style="background-color:red; width:560px; height:315px;"></div>

jQuery:

$('#video').on('click', function() {
    $(this).html('<iframe width="560" height="315" src="//www.youtube.com/embed/9bZkp7q19f0?autoplay=1" frameborder="0" allowfullscreen></iframe>').css('background', 'none');
});

If you want the video to autoplay add ?autoplay=1 to the end of the url as I did.

Code without thumbnail: http://jsfiddle.net/KFcRJ/

To extract video thumbnail:

HTML:

<div id="video" style="background-color:red; width:560px; height:315px;">
<a href="http://www.youtube.com/watch?v=9bZkp7q19f0" class="youtube"></a></div>

jQuery:

$('#video').on('click', function() {
$(this).html('<iframe width="560" height="315" src="//www.youtube.com/embed/9bZkp7q19f0?autoplay=1" frameborder="0" allowfullscreen></iframe>').css('background', 'none');
});

function getYoutubeID(url) {
    var id = url.match("[\\?&]v=([^&#]*)");
    id = id[1];
    return id;
};
$('a.youtube').each(function() {
    var id = getYoutubeID( this.href );
    this.id = id;
    var thumb_url = "http://img.youtube.com/vi/"+id+"/maxresdefault.jpg";
    $('<img width="100%" src="'+thumb_url+'" />').appendTo($('#video'));
});

Code with thumbnail: http://jsfiddle.net/89uVe/4/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top