YouTube Performance Switcheroo
I was really happy with my YouTube intro vid for GeoPortal. I wasn’t happy with what it did to my page load time. It added >1s to the load time, ~300KB to the page weight, and did some unpleasant style flashing as the player loaded. For a video that some users would watch once, that sucks. Time to give it the forearm shiver.
Faster YouTube embeds is not a new idea. It involves putting an image where the YouTube video is going to go, along with a play button, and then building the iframe on the fly if somebody clicks on it. I found a number of plugins for this using jQuery, but GeoPortal doesn’t use jQuery. I took my favorite by Jesse Schoberg and recreated it in plain JavaScript.
The container has an optional data-background
argument so you can specify an image to stick in there. By default it pulls the default image for the video from YouTube. The id
tag is the YouTube id, and the data-params
are appended to the URL. The JavaScript picks up anything with identifier you pass to it, in this case youtube
.
1 | <div class="youtube" id="DtEIu-h2FQo" data-params="controls=0&showinfo=0&rel=0" data-background="img/youtube-bg.png"></div>; |
The CSS is almost entirely from Jesse Schoberg’s code. It’s dropping a responsive play button in the middle of the container.
1 | .youtube { /* container (responsive) */ |
And now to the JavaScript, which I’ve rewritten into plain JavaScript as a CommonJS module.
1 | function youtubeLoader(identifier) { |
To call it, do a youtubeLoader('.youtube');
.
The results are pretty dramatic. With the YouTube vid directly in the page, page load time was 1.4s, page finish time was 2.14s, and page weight was 934kb. By using the above to load the YouTube iframe on demand, page load time went down to 0.633s, page finish time went down to 0.735s, and page weight went down to 652kb. That’s a serious, noticeable performance boost. As an added bonus, no more ugly style flashing from the YouTube iframe on page load.