If you’ve ever paid attention to a speed test on a website with a YouTube embed, you’ve probably seen something like this:
(results from http://www.webpagetest.org/)
A single YouTube embed can load up to 400KB of data before you even hit the play button. They also force the visitor’s browsers to make extra http requests. On a site with multiple videos embedded (like above), the extra weight can noticeably slow down load speeds (but even one embed makes a difference).
“On Demand” YouTube Loading
I found a solution in this article which describes the method Google+ uses to display videos. Instead of embedding the full player upon page load, it only displays a thumbnail with a play button overlayed. Resources for the YouTube player aren’t loaded unless a visitor actually clicks on a play button which 100% takes care of the issue described above.
The change is simple. Instead of using this old embed code:
<iframe src="https://www.youtube.com/embed/LcIytqkbdlo" height="180" width="320"></iframe>
Embed the video with this code:
<div class="youtube" id="LcIytqkbdlo" style="width: 320px; height: 180px;"></div>
So far, I’ve seen a size decrease of around 300KB per video in my experiments using this alternative embed code. Not bad for a little extra work!