Improve Page Speed with Lazy Loading for YouTube Embeds

Have you ever noticed how long it takes for your web page to load when you have embedded YouTube videos?

Or any heavy JavaScript payload?

The impact of these videos on your page's performance can be significant, especially when you have multiple videos on a single page. This can cause frustration for your visitors who want to access your content quickly. Fortunately, there is a solution to this problem: lazy loading. By implementing this technique, you can reduce the load time of your page and improve the overall user experience.

In this article, we'll explore the concept of lazy loading and how it can help you to speed up your page with embedded YouTube videos. You will see how YouTube loading can be mitigated by delaying its heavy scripts till the user wants to watch the video. This way you can delay loading the video until it is required.

At the moment I am working with the team to create the next version of C# Corner. Part of that update is to make the video more prominent. We also want to improve page speed. This means the site must have a way to lazy load YouTube video scripts. That is what I am going to share with you today.

Lazy Load YouTube Embeds

What is Lazy Loading?

Lazy loading is a technique that allows web developers to defer the loading of certain resources until they are actually needed. In the context of YouTube embeds, lazy loading allows you to delay the loading of the heavy YouTube player script until the user interacts with the video. This can significantly improve page performance, especially on pages with multiple videos.

The way it works is simple: instead of loading the entire YouTube player script when the page loads, you load a small placeholder image or a thumbnail of the video. Then, when the user clicks on the thumbnail, the YouTube player script is loaded, and the video starts playing.

The benefits of lazy loading are numerous. First, it reduces the page loading time, which can help improve the user experience and keep visitors engaged. Second, it reduces the amount of data transferred, which can help reduce bandwidth costs. Finally, it can help improve the search engine rankings of your pages by improving the page speed scores.

Here's an example of the simple lazy loading module, the new site will use. You are welcome to use the module to implement lazy loading on your pages too:


(function (window, undefined) {

    function initialize() {

        let n,
            v = document.querySelectorAll(".youtube-player, .video-hero-container");

        for (n = 0; n < v.length; n++) {

            if (!v[n].dataset.clickHandler || v[n].dataset.clickHandler !== "true") {

                v[n].dataset.clickHandler = "true";

                v[n].addEventListener("click", triggerVideoPlayer);

            }

        }

    }

    function triggerVideoPlayer(e) {

        e.preventDefault();

        let videoId = e.currentTarget.dataset.id;

        // load YouTube API script
        let tag = document.createElement('script');

        tag.src = 'https://www.youtube.com/iframe_api';

        let firstScriptTag = document.getElementsByTagName('script')[0];

        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        // create container element for player
        let playerContainer = document.createElement('div');

        playerContainer.className = 'player-container';
        e.currentTarget.parentNode.replaceChild(playerContainer, e.currentTarget);

        // get dimensions of the container
        let containerWidth = playerContainer.offsetWidth;
        let containerHeight = containerWidth * 0.5625; // 9/16

        // initialize player
        let player;


        window.onYouTubeIframeAPIReady = function () {

            player = new YT.Player(playerContainer, {
                height: containerHeight,
                width: containerWidth,
                videoId: videoId,
                events: {
                    'onReady': onPlayerReady
                }
            });

        }

        // start playing when player is ready
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        return false;

    }


    initialize();

    window.lazyYT = {
        initialize: initialize
    };


})(window);

This module will automatically detect all the YouTube embeds on your page and replace them with a lightweight placeholder. When the user clicks on the placeholder, the script will load the YouTube player script and start playing the video.

It also exposes the initialize method so you can set up lazy loading on any new HTML you might add to the page after it loads. Just call lazyYT.initialize(); to bind the process to any new video placeholders.

Here is an example of what a video looks like in HTML:

<div class="video-card">
    <div class="video-list-item youtube-player" data-id="lChoEaj3RnI"> 
    <img src="https://img.youtube.com/vi/lChoEaj3RnI/sddefault.jpg"
            srcset="https://img.youtube.com/vi/lChoEaj3RnI/maxresdefault.jpg 1280w,
                    https://img.youtube.com/vi/lChoEaj3RnI/sddefault.jpg 640w,
                    https://img.youtube.com/vi/lChoEaj3RnI/mqdefault.jpg 480w,
                    https://img.youtube.com/vi/lChoEaj3RnI/hqdefault.jpg 320w,
                    https://img.youtube.com/vi/lChoEaj3RnI/default.jpg 120w"
            sizes="(min-width: 1280px) 1280px, (min-width: 640px) 640px, (min-width: 480px) 480px, (min-width: 320px) 320px, 120px"
            alt="GitHub Actions vs Azure DevOps pipelines: Explore The Best Option For Your Deployment"
            loading="lazy" class="video-list-img" /> 
    </div>
    <div class="video-list-item-body">
        <p class="recent-post-description">Tempore dignissimos ad debitis sit. Adipisci
            molestiae totam quibusdam tenetur ullam neque. In dignissimos soluta
            repellendus occaecati fuga illum. Maiores quia consequatur accusantium
            fugit.</p>
        <h5>GitHub Actions vs Azure DevOps pipelines: Explore The Best Option For Your
            Deployment</h5>
        <div class="video-list-item-detail-row"> <span class="author-row-item"><i
                    class="fa-regular fa-clock"></i>2022-09-02 15:58:40.920&nbsp;</span>
        </div>
    </div>
</div>

That is a lot less code than if you embedded the video directly. Plus no YouTube scripts have been loaded from the external domain/origin.

This is what it looks like:

Example Lazy Loaded YouTube Thumbnail

After the user presses play the video loads. I set mine to automatically play, and most of my clients have asked for this feature. I will note that some browsers and devices disable the ability to auto-play videos, particularly on mobile devices. You should set your client's expectations for this, as it is out of your control.

A Lazy Loaded YouTube Video Playing

Lazy Loading YouTube Embeds

YouTube embeds are known to be a performance hog, slowing down page rendering and causing longer load times. However, by using lazy loading, you can improve the performance of your website and provide a better user experience. Lazy loading is a technique that delays the loading of non-critical resources until they are needed. In the case of YouTube embeds, the embed code is only loaded when the user requests to watch the video.

To lazy load YouTube embeds, you can modify the standard YouTube embed code by adding a few extra attributes to the iframe element. The two most important attributes are data-src and loading="lazy". The data-src attribute is used to store the URL of the YouTube video, while the loading attribute is set to lazy, which tells the browser to load the video only when it's needed.

To make things easier, you can also use a pre-built script, like the lazy-loading YouTube script we created earlier. This script automates the process of lazy loading YouTube videos, so you don't have to modify the embed code manually. Here's how to implement it:

  1. Download the lazy loading YouTube script from my public GitHub Repo.
  2. Include the script in your HTML file using a script tag.
  3. Add the youtube-player class to any element that contains a YouTube embed you want to lazy load.
  4. Add the data-id attribute to the element and set its value to the ID of the YouTube video you want to embed.
  5. That's it! The lazy-loading YouTube script will automatically replace the original embed code with the lazy-loading code when the user clicks on the element.

By lazy loading YouTube embeds, you can significantly improve the performance of your website and provide a better user experience for your visitors.

Best Practices for Lazy Loading YouTube Embeds

Lazy-loading YouTube embeds can greatly improve the performance of your web pages. However, it's important to follow some best practices to ensure a smooth user experience. One of the most important practices is to use a thumbnail image as a placeholder for the video. This not only helps to reduce the initial page load time but also gives users an idea of what the video is about before they click to play it.

People have been trained to see a thumbnail for videos. It does not matter if it is YouTube, Hulu, Netflix, etc, the thumbnail sells the video. So my advice is to follow the paradigm in your applications.

Another best practice is to set the video to load only when it's in view. This is achieved by using a technique called "Intersection Observer", which is available in modern browsers. By only loading the video when it's in view, you can further reduce the page load time and improve performance. More on that in another article.

Pro Tip: Always add the loading="lazy" to any img you have in your pages. This uses the browser's built-in lazy loading functionality. That way you do not need to write any code in your application. Anytime you can use a native performance feature do it.

When using our lazy load module for YouTube embeds, follow these best practices to ensure the best user experience.

Conclusion

By implementing lazy loading for YouTube embeds on your website, you can greatly improve page performance by reducing the impact of large payloads, such as JavaScript, that can slow down page rendering. By using a thumbnail image and setting the video to load only when it's in view, you can further optimize the user experience.

Using the lazy load module provided in this article, along with the step-by-step instructions, you can easily implement lazy loading for your YouTube embeds. Don't let large payloads affect your page speed and user experience any longer. Give lazy loading a try on your own site and see the difference for yourself.

FAQs

Q: How can I test the performance of my website after implementing lazy loading for YouTube embeds? A: There are several online tools available such as Google PageSpeed Insights, WebPageTest.org (my favorite), or the Lighthouse tool built into both Edge and Chrome developer tools that can help you test your website's performance and identify any potential issues.

Q: Are there any SEO concerns with lazy loading YouTube embeds? A: No, there are no SEO concerns with lazy loading YouTube embeds as long as you use proper markup and ensure that the video content is accessible to all users.

Q: Can lazy loading be applied to other types of embedded content besides YouTube videos? A: Yes, lazy loading can be applied to any type of embedded content, including images, videos, and iframes, to improve page performance.

Q: Is it possible to customize the thumbnail image that's displayed for the lazy-loaded YouTube video? A: Yes, you can customize the thumbnail image by specifying a custom thumbnail URL in the YouTube embed code.

Q: Are there any common mistakes to avoid when implementing lazy loading for YouTube embeds? A: Some common mistakes include not testing the lazy loading functionality on different devices and browsers, not providing alternative content for users who have disabled JavaScript or are unable to view the video content, and not properly setting the dimensions of the video container to avoid layout issues.


Love2Dev
We specialize in Progressive Web Apps and Web Performance Optimization