When you embed a YouTube video in your web page, did you know a visitor's browser would have to download an extra ~400Kb just to render the player alone?

Load YouTube video like Google+

That's 7 files for a flash based player and the number is 12 if a HTML5 player is used - something not really under your control. These include image files, css, xml and javascript and the bad part is - they will always download even if the visitor doesn't actually play the embedded video. The extra weight(~.4Mb) and 7-12 additional HTTP requests only adds to slowing down your pages indirectly.

Not to mention, your site's overall loading time also goes high in the eyes of Google and other search engines where it is a significant factor for calculating page rank.

Embed Youtube Videos Google+ style.

Have you noticed how Google plus posts show YouTube videos with a slightly different play button? Well, that's a cleaver trick by Google+ where instead of embedding the full YouTube player, only a preview thumbnail of the video is displayed with a custom play button on top to make it look like a player. And when you click over it, the image is replaced by the standard YouTube player which will then load and play automatically.

That means any player specific resources are loaded only once a visitor actually chooses to play the video and not otherwise.

You can also use the same technique in your website to shorten page loading time while embedding YouTube videos. And here's a trick that will let you do it without changing any of your existing code.

Making YouTube Video Iframes Like Google+

First, download and add the following javascript file to the header section of your page.

gplus-youtubeembed.js

Next you need to call the "optimizeYouTubeEmbeds" function that will make your YouTube video embeds like the Google+ one. To do that, add the following code just before the ending </body> tag of your page.

<script type="text/javascript">optimizeYouTubeEmbeds()</script>

That's it. Now all YouTube video embeds in the page will load only on-demand. The code has been tested on IE, Firefox, Chrome and Opera.

Here's a working example.

How It Works.

The "optimizeYouTubeEmbeds()" function quickly scans to find out all embedded YouTube iframes and replaces them with the video preview image & play button just like Google+. Since it gets called right at the end of the body, the browser doesn't get a chance to download the player or any associated resources while rendering the page.

Adding this small piece of code will take away ~.4Mb weight out of your web page and improve user experience. If you are interested in knowing more about the code, here's where it is explained. Please do like/follow/plus me if this was useful to you. And as always, if you encounter any problems, please do let me know as comments.

IMPORTANT: If yours is a high traffic site, make sure to download a local copy and use that instead.