Reduce The Loading Time Of YouTube Video Player: Load YouTube Videos Onclick
Depending on the internet connection speed, the YouTube video player can take a significant amount of time to load in the visitor’s browser. If you have a webpage where you have embedded a good number of YouTube videos, it might slow down the page on the client’s end. This is because the YouTube video player downloads additional resources and files, even before the visitor chooses to watch the video that is embedded within your page.
So unless of course the visitor is interested in watching a video, it makes no sense hogging down your webpage and make it load slow. If you have a video gallery or a page that contains a mix of content, photos and videos, it is indeed a good idea to
- First load the entire webpage so that the reader can start reading as early as possible.
- Load the images, then the scripts and other additional elements in the background
- Load videos, flash content and other embedded content on demand (why force the whole webpage to load all the elements one after another without knowing the user’s intent)
Technology blog Digital Inspiration shares a very useful hack which lets you load YouTube videos on demand. You can use this trick to reduce the loading time of YouTube’s video player and make it load only when the visitor clicks the link or video thumbnail.
Here is how it works.
Click the following thumbnail to see how the YouTube video player loading on demand. The video player will load only when the thumbnail is clicked, so the video player does not come in the way of this webpage and does not affect its loading time to that extent.
The general way to embed a YouTube video is to use the iFrame embed code (you can also use the old embed code but iFrame works better in some situations). However, in order to load YouTube videos only when they are clicked, you can use the following code
<div class=”youtube” id=”XXXXXXXXXXX” style=”width: 320px; height: 180px;”></div>
Note: Remember to replace the ID of the video with the ID of the video you want to embed in your page. You can further customize the width, height and other options of the YouTube video player. For more help, be sure to check out the developer documentation here.
The code uses a custom thumbnail for the YouTube video so it might not look very pretty when multiple videos are embedded one after another. However, this works great if you want to load YouTube videos on demand and not on default page load.