My site loads slowly due to too many embedded videos

My site loads slowly due to too many embedded videos. I can see where the image is (the inscription where the video is embedded), and you click on it, after which the embedded video is loaded. Can someone help me figure out how to do this? Maybe after you hover over the image, you insert youtube if it is loaded? Thank you very much!

+6
source share
1 answer

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

Just a 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 start automatically, add ?autoplay=1 to the end of the URL, just like me.

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

To extract a thumbnail of a video:

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')); }); 

Thumbnail code: http://jsfiddle.net/89uVe/4/

+11
source

Source: https://habr.com/ru/post/956828/


All Articles