Lazy Loading Youtube Videos

Fri Jan 11 2019

1 Background

The concept of lazy loading is a design pattern where you only download the required scripts/content when the client needs it rather than when the page is loaded. The most iconic example is the “infinite” feed that social media sites like Instagram use. Rather than dump a ton of content to the client at once, Instagram dynamically loads more content once you reach the end of the page. This allows websites to save bandwidth by only sending the client what they need when they need it.

When a youtube video is embedded into a website, it pulls a ton of scripts which are required to play the video. However, when you embed a youtube video on a blog post, most people are not going to watch that video. Even if the visitor wanted to watch that video, there is no reason why all the scripts should be loaded when you initially land on the page. Rather than embed the video normally, you can instead simply have a the thumbnail of the video with a play button on it. When the client clicks the play button, the youtube scripts are then loaded.

2 Performance Without Lazy Loading

A very basic blog post with two Youtube videos is 1.5 MB in size. That is a rather large page for a client to download and render. Notice that 65% of the content by size is from Youtube and 29 requests were from Google domains.

3 Performance with Lazy Loading

After lazy loading Youtube videos I was able to reduce the size of this blog post by nearly 1 MB. This also decreased the page load time by 75%. Additional tests show’s that each embedded youtube video consumes around 500 KB. Using the lazy loading method you can slash that 500 KB to a mere 100 KB– size of just the thumbnail.

4 Code Used

4.1 Javascript

This is some basic JavaScript code which selects all of the “youtube” embedded videos on our page and adds a play button handler. When the button is clicked, it updates the div to have an Iframe with the appropriate embedded youtube video. If you are already using jQuery, you could use that but, I did not since the goal of this is to optimize the page load time. The jQuery library is nearly 50 KB.

4.2.1 Example

4.3 HTML

Rather than use the embed code that youtube provides, you have to use the following code to integrate with the CSS and JS written. All you need from the youtube video is the ID which appears in the link associated with that video.

4.4 Node Templating Stuff

When witting blog posts in Markdown, it is not convenient to include 5 lines of HTML to embed a video. On my node server I wrote some code to convert a simpler “youtube tag” into the 5 lines of HTML shown above. This is completely optional.