search ]

How to Defer JavaScript for Youtube Videos

Delaying Javascript, in other words, Defer parsing of Javascript, is one of the messages you might receive when checking your website’s speed using tools like GTmetrix and Pingdom.

This message indicates that the browser needs to process content within a specific <script> tag before it can continue loading the rest of the page. By delaying the processing of that script until it’s actually needed, we can improve loading time and Core Web Vitals scores.

We won’t delve further into this, and in this post, we will focus exclusively on deferring Javascript for YouTube videos. If you’re interested in a more comprehensive explanation of the topic, take a look at the post How to Defer Javascript in WordPress Sites.

In one of the websites where I optimized speed and loading time, there was a YouTube video on the homepage. The page received a low score in speed testing tools, and I had to do something to address it.

The main issue was Defer Parsing of Javascript, as three of those problematic scripts were scripts from youtube.com. Here’s the note I received in GTmetrix:

Defer Parsing of Javascript for YouTube

The scripts from youtube.com that you see in this image delayed the page load. In other words, only after these scripts were loaded (and note that these are heavy scripts), the rest of the page continued loading.

How to Delay Javascript for YouTube Videos?

Let’s explain how to solve this issue. When you embed a video in WordPress by copying the video’s URL from YouTube or Vimeo, WordPress generates an <iframe> for that video.

It’s essentially the same <iframe> you would get if you directly copied the embed code from YouTube.

Instead of using the URL to embed the video, go to YouTube and copy the embed code in the following way:

  • Under the video, click on “Share“.
  • Click on “Embed” that appears below it.
  • Make any necessary changes in the embed options.
  • Copy the embed code starting with “…iframe width>“.

Then, go to your website and paste the <iframe> code where you want to display the video. The next step will be to slightly modify this code:

  • Find the part src=”https://www.youtube.com and change src to data-src.
  • Add an empty parameter named “”=src. Ultimately, this will contain the URL from the data-src parameter that we just added.

Ultimately, your <iframe> code will look like this:

<iframe width="560" height="315" src="" data-src="https://www.youtube.com/embed/123456789" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="border:0"></iframe>

Triggering Video Loading After Page Load Using Javascript

The <iframe> we’ve created so far won’t load the video properly. Let’s add a bit of Javascript to load it only after the page has fully loaded.

function init() {
  const iframes = document.querySelectorAll('iframe[data-src]');
  iframes.forEach((iframe) => {
    iframe.setAttribute('src', iframe.getAttribute('data-src'));
  });
}
window.addEventListener('load', init);

This code copies the data-src attribute to the src attribute after the page has loaded. When this happens, the YouTube video will be displayed on your page.

Notice the differences in GTmetrix results before and after applying this technique.

If you’re unsure how to add Javascript to your website, take a look at the post Adding Assets (Javascript and CSS Files) in WordPress.

Before Delaying Javascript for Videos:

GTmetrix score before deferring video

After Delaying Javascript for Videos:

GTmetrix score after deferring video

Notice that the score, server requests, and page size significantly improved. The score under Defer Parsing of Javascript jumped from F to A, and the warnings we mentioned at the beginning of the post disappeared.

Additional Considerations

In the case of the site where I optimized, the video was only present on the homepage. I ensured that the JavaScript code would only load on the homepage by adding a condition within the wp_enqueue_scripts function.

It’s worth noting that this code will affect only <iframe> elements with the data-src parameter, so you don’t need to worry about it affecting other videos on your site that don’t have this parameter.

Another way to improve the loading time of embedded YouTube videos is the facade pattern, covered in the post Improving Loading Time of Embedded Videos with Lite YouTube.

If you find that the YouTube videos on your site aren’t responsive, check out the post explaining How to Make YouTube Videos Responsive in WordPress.

The Native loading=”lazy” Attribute

Modern browsers support a native loading="lazy" attribute for iframes. Adding this attribute tells the browser to defer loading the iframe until it is near the viewport:

<iframe src="https://www.youtube.com/embed/123456789" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="border:0"></iframe>

This is the simplest approach and works without any JavaScript. However, it only defers the loading – the YouTube player and its scripts still load once the iframe enters the viewport, even if the user never clicks play.

For the best performance, combine loading="lazy" with the data-src technique shown above. The lazy attribute handles below-the-fold videos, while the data-src approach handles above-the-fold videos that should only load after the page is ready.

The Facade Pattern – A Modern Alternative

The most effective approach for YouTube embeds is the facade pattern. Instead of loading the full YouTube player, you display a lightweight placeholder (just the video thumbnail) and only load the actual player when the user clicks play.

This is what libraries like lite-youtube-embed do. They load approximately 224x faster than standard YouTube embeds because the initial load is just a static image and some CSS.

Google’s Lighthouse tool specifically recommends this approach under the “Lazy load third-party resources with facades” audit. For a detailed implementation guide, see our post on Improving Loading Time of Embedded Videos with Lite YouTube.

Impact on Core Web Vitals

A standard YouTube embed loads multiple scripts, stylesheets, and other resources even when the user never plays the video. This directly impacts your Core Web Vitals:

  • LCP (Largest Contentful Paint) – YouTube’s scripts block the main thread, delaying the rendering of your largest content element.
  • INP (Interaction to Next Paint) – The additional JavaScript increases main thread work, making the page less responsive to user interactions.
  • Page weight – A single YouTube embed adds approximately 800KB to your page size.

Deferring or replacing the embed with a facade eliminates this overhead entirely until the user actually needs the video.

FAQs

Common questions about deferring YouTube JavaScript:

Does deferring YouTube JavaScript affect the video's appearance?
With the data-src technique, the video area will appear empty until the page finishes loading, then the YouTube player will appear normally. With the facade pattern, a thumbnail image is shown immediately, and the full player loads only when the user clicks play. Both approaches result in a fully functional video once loaded.
What is the difference between loading="lazy" and the data-src technique?
The loading="lazy" attribute is a native browser feature that defers loading the iframe until it is near the viewport. The data-src technique prevents the iframe from loading at all until the page has finished loading. For above-the-fold videos, the data-src technique or facade pattern is more effective. For below-the-fold videos, loading="lazy" alone may be sufficient.
Will this technique work with Vimeo or other video platforms?
Yes. The data-src technique works with any iframe-based embed, including Vimeo, Dailymotion, and other video platforms. The JavaScript code targets all iframes with a data-src attribute regardless of the source URL. The facade pattern libraries, however, are typically platform-specific.
How much does a YouTube embed affect page speed?
A single standard YouTube embed adds approximately 800KB to your page and loads multiple scripts from youtube.com. This can significantly impact Largest Contentful Paint (LCP) and Interaction to Next Paint (INP). Deferring or using a facade can reduce this initial impact to near zero.
Should I use the data-src technique or the facade pattern?
The facade pattern is the recommended approach for best performance. It shows a thumbnail immediately and only loads the YouTube player on click. The data-src technique is simpler to implement and does not require additional libraries. Choose the facade pattern for maximum performance and the data-src technique for simplicity.
Does WP Rocket handle YouTube deferring automatically?
WP Rocket includes a "LazyLoad for iframes and videos" feature that automatically replaces YouTube embeds with a thumbnail placeholder. When enabled, it works similarly to the facade pattern without requiring manual code changes. If you use WP Rocket, enable this option in the Media section of the plugin settings.

Summary

Deferring JavaScript for YouTube videos is essential for maintaining good page performance. The simplest approach is the data-src technique combined with loading="lazy", which delays loading until the page is ready.

For maximum performance, the facade pattern using libraries like lite-youtube-embed is recommended, as it loads only a static thumbnail until the user clicks play. Whichever method you choose, the impact on Core Web Vitals is significant – reducing page weight by hundreds of kilobytes and freeing up the main thread for faster rendering.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo