Deferring parsing of JavaScript is one of those messages that you get on sites like GTmetrix and other page speed sites that may sound like it’s from another planet. What on Earth does defer parsing of JavaScript even mean? Basically, what the message is saying is that a browser needs to process all of the content inside <script>
tags before it can load the page. By putting off the processing of JavaScript until it is actually needed, you can reduce the initial load time of your page.
Defer Parsing of JavaScript YouTube Videos
I had a site with one YouTube video on the home page. The home page, when loaded was getting a low score in GTmetrix, and I wanted to do something to change it. The worst offender was Defer Parsing Of JavaScript, which had 13 scripts being loaded on the initial page load. Six of those were from youtube.com!
When you embed a video in WordPress by copying and pasting the video’s URL from sites like YouTube, Vimeo, etc. WordPress creates an <iframe>
for that video. It’s basically the same <iframe>
code that you’d get by copying the embed code directly from YouTube.
So, instead of using the URL to embed the video, go to YouTube and copy the <iframe>
embed code.
- Under the video, click the Share button
- Towards the bottom, click the Embed button
- Make any adjustments to the Embed Options you may need
- Copy the embed code at the top that starts with
<iframe width=
Next, come back to your site and paste that <iframe>
code where you want it to go on your site.
You’re going to need to change a bit of the <iframe>
code.
- Find the
src="https://www.youtube.com...
and changesrc
todata-src
- Add another empty parameter
src=""
. This replaces thesrc
we just changed todata-src
Your <iframe>
should look something like this now:
<iframe src="" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen" data-src="https://www.youtube.com/embed/123456789"></iframe> |
The JavaScript
The <iframe>
we set up by itself won’t load the video correctly. We’ll use some JavaScript to get it to load correctly.
function init() { var vidDefer = document.getElementsByTagName('iframe'); for (var i=0; i<vidDefer.length; i++) { if(vidDefer[i].getAttribute('data-src')) { vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src')); } } } window.onload = init; |
The next time I ran the GTmetrix test on that page, the Defer Parsing of JavaScript score went from an F (0) to a B (85). Initially, there was 2.2MB of JavaScript being loaded during the initial page load. After optimizing, it was down to about 168KB.
Other Considerations
In my case the video was only on the home page, so I made sure the JavaScript file only loaded on the home page. In the future, if I have other pages that need this adjustment, I can add them to this conditional in my wp_enqueue_scripts
function. If the video is set up the same way, you shouldn’t need any other JavaScript to load other videos on your site as the JavaScript looks for any <iframe>
elements that have a data-src
attribute.
Also, special thanks to Patrick Sexton, for the initial guidance for this post.
Hi, it worked for me but the video stopped being responsive.
Is there a way to keep responsiveness?
You can do that with some CSS. Check out this tutorial for some guidance: https://benmarshall.me/responsive-iframes/
Where does the Css from this tutorial from Ben go?
You would need to add that to either (1) your child theme’s style.css, (2) the Appearance > Customize > Additional CSS, or (3) in a custom stylesheet in a plugin. #2 is probably the easiest place to put it.
Where do I need to paste this Javascript Code?
You would need to add it to it’s own JS file and enqueue it on your pages as needed. Check out the codex source for how to do this.
Hello im having issues with doing this where i can now not pause the video?
HI Scott,
Thanks for the very helpful script.
I added it to our homepage with the Google tagmanager. In about 50% of the cases, i.e. page reloads it doesn’t work: blank space where the videoplayer should appear (to wait further doesn’t help…). Any idea what I am doing wrong. Page load speed drops from 0.952 s to 0.781 s with your script. Thats cool actually.
Great trick! Thanks a lot!
Hi can you please tell me which is the file where I have to paste the last Javascript code. I am not so good about coding
Thanks
You will have to create a JS file and include it in your plugin with the wp_enqueue_scripts function.
My site home page have 4 youtube videos
only first iframe src apply working other three iframe src value is “unknown”.
I did this with only one video on the page, so I can’t say for sure how it will work with multiple videos. But you can try something like this (untested) code:
function init() {
var vidDefer = document.getElementsByTagName('iframe');
var iframes = Array.prototype.slice.call(vidDefer);
iframes.forEach(function(iframe) {
if(iframe.getAttribute('data-src')) {
iframe.setAttribute('src',iframe.getAttribute('data-src'));
}
}
}
window.onload = init;
Incredible advice. Changed the two YouTube videos on the home page of my site and just went from an ‘F’ grade in defer parsing of JavaScript on GT Metrix for a 100% ‘A’. Can’t thank you enough.
Now – next question. I have over 200 other YouTube videos on my site. Do I have to change each of those individually to help the load speed for those (if I’m sending people to those individual pages via social media) or is there a better way?
You shouldn’t need to add the JavaScript for each video (the one time is sufficient), but the
src="" data-src="https://youtube.com/..."
bit will need to be modified for each video to get the benefit.Hi! First thing I’ve tried to defer parsing of JavaScript was to activate the option in the cache plugin I use (Litespeed Cache), but I had some visualization problems about Rev Slider and translation plugin also (Transposh), so I excluded the corresponding JS of deferring, but not fixing the error… After that, did the same but using Fast Velocity Minify plugin instead, same results. Maybe adding the code to functions.php skipping these problematic JS could be the solution but, how can I exclude it by code?
Many thanks for the help!
Great! It worked for me. Saved me the trouble
Glad it worked for you Kelvin!
Hi Scott,
Great tutorial. But not working on Firefox. I mean, no display.
Try clearing the browser’s cache and use a Private Window (CTRL + Shift + P) so no browser extensions are conflicting with what’s on the page.
It should work on any browser.
You did not mention for newbies where to paste that Java Script Code ?
in tag or after tag?
Where?
You could place that in a separate JavaScript file and use the WordPress wp_enqueue_script() function to load it as needed.
Some themes also have a way to add scripts to individual pages, which should work as well.
Hello Scott how are you? I am new to wordpress and I have been searching a lot to solve the problem with render-blocking javascript on the website that I’m making.
I tried to implement this solution on my website but the elementor page builder doesn’t accept the HTML code to embed the video into the page. Its gives me an error.
My HTML for the video has this format:
I also created a .js file with this code and Iv’e put it into my site’s main folder:
function init() {
var vidDefer = document.getElementsByTagName(‘iframe’);
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute(‘data-src’)) {
vidDefer[i].setAttribute(‘src’,vidDefer[i].getAttribute(‘data-src’));
} } }
window.onload = init;
And in my theme’s functions.php file I have added the function to enqueue the script like this:
function enqueuescripts() {
wp_enqueue_script (‘miguel’,’videos.js’, false);
}
add_action( ‘wp_enqueue_scripts’, ‘enqueuescripts’ );
Do you spot what may be wrong?
Thank you very much in advance!
In your
wp_enqueue_script()
function, you need to make thevideos.js
either the full URL to the file, or a path of the file relative to the WordPress root directory.Something like:
wp_enqueue_script( 'miguel', 'https://yoursite.com/wp-content/themes/your-theme/videos.js', false );
Or:
wp_enqueue_script( 'miguel', get_template_directory_uri() . '/videos.js', false );
You should be able to tell if the correct file is loading by viewing the source code of your site to see if the videos.js file shows up or not.
Brilliant! Thank you.
It is not working if you use AMP.
I haven’t had the opportunity to use this on AMP so unfortunately I don’t really know what changes you would need to make to get it to work.
I really appreciate this post. I want to point out to anyone copy/pasting that an error has made its way into the code with < in there, which causes an unexpected line ending in the for area on the third line. I went a slightly different route based on the code that you made, instead targeting by class with getElementsByClassName – now I just put any youtube embeds into a defer-youtube class and they no longer block page rendering.
I serve a copy of jquery.min.js and slipped this into the very end of the file to avoid having 1 more request just for this tiny bit of code. Thanks a lot for sharing.
Hey Carl,
On a WordPress site, it’s recommended that you serve the copy of JQuery that is packaged with WordPress instead of rolling your own. This helps avoid conflicts between your version and another version that might be loaded by a plugin, theme, or even WordPress itself. I get what you’re trying to do by avoiding one extra request, but with the right optimization plugin (i.e. Autoptimize, etc.) you can combine all of the JS files that get loaded into just one file anyway.
hey there
thanks for the great script
Any ideas how can I disable the suggested videos at the end of the video
PLEASE?
YouTube used to let you add a
?rel=0
at the end of the video’s URL, which would disable all related videos. It turns out a few months ago they changed the behavior of this to include related videos from the account the video came from. There is no easy way to disable related videos anymore. This site has some details that might work for you, although I haven’t tested any of it on my end.If you make all the videos in your channel unlisted, then the ?rel=0 still works fine. As long as you don’t mind them not being listed, it’s god solution.
Thanks for your js code and css for responsive – all worked first time on desktop and mobile. Really, really cool!
Hi Scott,
Thanks for the post. I am tyring to defer the javascript for a youtube video on my homepage, it’s not a wordpress site, where would I add the javascript in this case, in the main.js? In the other comments instructions are for wordpress. We’re in the process of changing to a wordpress site but we need to make the current site usable in the meantime. Thanks!
Hi Alex,
I suppose it depends on how your site is set up. If your site already has a custom JavaScript file that you can add to, then it should work. You just need to make sure that the JavaScript file you are adding the code to is being loaded on the page(s) with the YouTube videos.
If you don’t have a JavaScript file available to add this to, I would suggest creating a separate file with the code from this example. Be sure to include the JavaScript file in your site’s
<head>
like this:<script type="text/javascript" src="https://yoursite.com/where-your-js-file-is-located/your-js-file.js"></script>
Great thanks Scott!
Fantastic! thank you so much for this simple and elegant fix. Perfect scores now.
🙂
I’m glad it helped!
Thanks! This is proven effective. I saved 6.2MiB!
thanks ,very helpful
Hi,
Just wanted to let you know that this helped me.
I went from F on GTmetrix to A.
Thank you very much.
Awesome, glad it helped you out!
İ tried it and worked for me really well. I thank you so much sir.
I am truly greatful for your help. I looked everywhere just to find a solution.
Hi Scott,
Thank you, it worked for me as well. Somehow I have the problem, that I can’t change the size of the video now (width and hights). If I change width and height nothing happens. That is my code.
Best regards
Richard
Hi, Scott,
I did in the same way as you wrote above, and the Google PageSpeed Insights tool also said that there is no YouTube JS on my page. But, the issue is that the YouTube video does not show on the page, and leaves blank.
Is there something wrong with my site? BTW, the site is not on WordPress.
THX in advance.
I’m guessing that the JavaScript code isn’t being loaded correctly on your site. That basically drops the YouTube URL into the
src
portion of the<iframe>
based on thedata-src
attribute. Either that or thedata-src
portion of the<iframe>
is not set up correctly. It shouldn’t matter whether you’re using WordPress or not, unless you have another CMS that is modifying<iframe>
somehow so that this code won’t work.Thank you so much!
It worked perfectly.
Hi Scott,
There’s a bug on iPhone / Workds on Desktop Windows 10 (Chrome…) and Android
The scripts works well but no video shown on iphone… 🙁
Thank you so much. It worked perfectly.
To those who don’t use wordpress, you can add the script code, after the tag in the html file. That works perfect to me!
Thank You Sir
It Really Work. It is perfect.
Thanks for the script. Will try this – and also want to try it on other iframes (Google Docs).
Do you know what the SEO effects will be – does it change what Google sees on the page.
Thanks
Hi Steve,
I don’t think it has any negative SEO effects. If anything it could improve SEO by improving the page load speed. Whether it actually improves SEO or not, I imagine that it would not have a huge effect though. Basically, this trick won’t put you at #1 in the search results, unless maybe you were already at a close #2.