• Skip to main content
  • Skip to primary sidebar
  • About
  • Contact
  • Resources
  • Blog
    • Easy Digital Downloads
    • General
    • Genesis Framework
    • jQuery/JavaScript
    • Project Management
    • WordPress Functions
    • WordPress Plugin Development
  • Army Lessons

Scott DeLuzio

WordPress Development Tutorials

Defer Parsing of JavaScript With YouTube Videos

October 30, 2017 Scott DeLuzio 64 Comments

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 change src to data-src
  • Add another empty parameter src="". This replaces the src we just changed to data-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>

<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;

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.
Defer Parsing of JavaScript With YouTube Videos

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.

jQuery/JavaScript

Reader Interactions

Comments

  1. jonatan says

    November 18, 2017 at 2:27 pm

    Hi, it worked for me but the video stopped being responsive.
    Is there a way to keep responsiveness?

    Reply
    • Scott DeLuzio says

      November 22, 2017 at 8:38 am

      You can do that with some CSS. Check out this tutorial for some guidance: https://benmarshall.me/responsive-iframes/

      Reply
      • Samuel Clark says

        June 14, 2018 at 3:27 pm

        Where does the Css from this tutorial from Ben go?

        Reply
        • Scott DeLuzio says

          July 23, 2018 at 11:14 am

          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.

          Reply
  2. Pranshu Kharkwal says

    January 30, 2018 at 10:12 am

    Where do I need to paste this Javascript Code?

    Reply
    • Scott DeLuzio says

      January 31, 2018 at 9:50 am

      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.

      Reply
  3. Joe says

    March 26, 2018 at 11:21 am

    Hello im having issues with doing this where i can now not pause the video?

    Reply
  4. cesare says

    March 27, 2018 at 6:23 am

    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.

    Reply
  5. Paul says

    May 6, 2018 at 1:11 pm

    Great trick! Thanks a lot!

    Reply
  6. ROGER GIOVANNY GUERRERO LEON says

    June 30, 2018 at 1:54 pm

    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

    Reply
    • Scott DeLuzio says

      July 23, 2018 at 11:09 am

      You will have to create a JS file and include it in your plugin with the wp_enqueue_scripts function.

      Reply
  7. Kanewilliam says

    August 3, 2018 at 7:38 am

    My site home page have 4 youtube videos

    only first iframe src apply working other three iframe src value is “unknown”.

    Reply
    • Scott DeLuzio says

      August 15, 2018 at 12:45 pm

      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;

      Reply
  8. Dan says

    August 11, 2018 at 11:14 am

    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?

    Reply
    • Scott DeLuzio says

      August 15, 2018 at 12:38 pm

      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.

      Reply
  9. Asdeideas Diseño says

    August 13, 2018 at 1:05 am

    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!

    Reply
  10. Kelvin Akpe says

    October 2, 2018 at 3:31 pm

    Great! It worked for me. Saved me the trouble

    Reply
    • Scott DeLuzio says

      October 2, 2018 at 4:05 pm

      Glad it worked for you Kelvin!

      Reply
  11. Zuphel Baguio says

    October 16, 2018 at 1:13 am

    Hi Scott,

    Great tutorial. But not working on Firefox. I mean, no display.

    Reply
    • Scott DeLuzio says

      October 16, 2018 at 10:22 am

      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.

      Reply
  12. jems says

    January 24, 2019 at 2:29 am

    https://www.youtube.com/watch?v=p1IU4hCMUjI
    Use below scripts for more video’s

    window.onload = function (){
    var hndl = document.getElementsByTagName(‘iframe’);
    for (var i = 0; i < hndl.length; i++){

    console.log(hndl);
    if (hndl[i].getAttribute('data-src')){

    console.log(hndl[i].getAttribute('data-src'));
    hndl[i].setAttribute('src', hndl[i].getAttribute('data-src'));
    }
    }
    }

    Reply
  13. Rizwan Wris says

    February 5, 2019 at 8:43 pm

    You did not mention for newbies where to paste that Java Script Code ?
    in tag or after tag?
    Where?

    Reply
    • Scott DeLuzio says

      February 6, 2019 at 10:00 am

      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.

      Reply
  14. Miguel says

    February 26, 2019 at 11:36 am

    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!

    Reply
    • Scott DeLuzio says

      February 26, 2019 at 2:21 pm

      In your wp_enqueue_script() function, you need to make the videos.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.

      Reply
  15. Dee says

    March 3, 2019 at 11:51 pm

    Brilliant! Thank you.

    Reply
  16. Dave says

    March 5, 2019 at 1:24 pm

    Hi Scott,

    Any idea why this isn’t working?

    https://www.ceutagroup.com/test/

    It’s the same video that’s on the home page, I’m trying to remove the need for the YT scripts… But I can’t get anything other than a blank screen using any method – JS in a file, in the head, foot, etc.

    Thanks

    Reply
  17. Vitaliy Yermakov says

    April 16, 2019 at 2:27 am

    It is not working if you use AMP.

    Reply
    • Scott DeLuzio says

      April 16, 2019 at 9:00 am

      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.

      Reply
  18. Carl says

    April 21, 2019 at 2:28 pm

    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.

    Reply
    • Scott DeLuzio says

      April 23, 2019 at 8:56 am

      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.

      Reply
  19. ojasya thakur says

    May 9, 2019 at 5:46 am

    hey there
    thanks for the great script

    Any ideas how can I disable the suggested videos at the end of the video

    PLEASE?

    Reply
    • Scott DeLuzio says

      May 10, 2019 at 10:36 am

      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.

      Reply
  20. Keith Rowley says

    June 5, 2019 at 3:35 pm

    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!

    Reply
  21. Alex says

    June 12, 2019 at 1:42 am

    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!

    Reply
    • Scott DeLuzio says

      June 12, 2019 at 9:53 am

      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>

      Reply
      • Alex says

        June 13, 2019 at 12:43 am

        Great thanks Scott!

        Reply
  22. Sandy Rowley says

    June 19, 2019 at 10:46 pm

    Fantastic! thank you so much for this simple and elegant fix. Perfect scores now.
    🙂

    Reply
    • Scott DeLuzio says

      June 20, 2019 at 1:49 pm

      I’m glad it helped!

      Reply
  23. Ernesto says

    June 21, 2019 at 4:38 pm

    Thanks! This is proven effective. I saved 6.2MiB!

    Reply
  24. Joffrey says

    July 1, 2019 at 11:03 pm

    Hi Scott,

    I tried to implement this solution on my website but the video doesn’t appear on my website.

    I’ve created myjava.js in my child theme folder with this code :
    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;

    Then add this in my functions.php :
    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;

    Reply
  25. Danny says

    July 23, 2019 at 1:14 pm

    Hello Scott,

    I am hoping you can help, my blogger html editor will not except the following code:

    for (var i=0; i<vidDefer.length; i++) {

    I have to remove the "<" as it thinks it's an opening tag & is looking for the close.

    Is their any other variation that I could use instead?

    Many thanks,

    Danny

    Reply
  26. Nadheem khan says

    July 28, 2019 at 10:46 pm

    Hello sir , I tried your solution for my project but for some reasons it’s not working. I have about 3mb of javascript files mostly all loaded from youtube , google captcha and facebook.
    Project Link: https://dbsom.in/
    Any help would be really appreciated.
    Thank you

    Reply
  27. deepika says

    August 8, 2019 at 12:16 pm

    thanks ,very helpful

    Reply
  28. DUOSHIRO says

    October 29, 2019 at 3:04 pm

    Hi,

    Just wanted to let you know that this helped me.

    I went from F on GTmetrix to A.

    Thank you very much.

    Reply
    • Scott DeLuzio says

      October 29, 2019 at 3:05 pm

      Awesome, glad it helped you out!

      Reply
  29. Engin says

    December 3, 2019 at 12:57 pm

    İ tried it and worked for me really well. I thank you so much sir.

    Reply
    • ENGİN ASAR says

      December 30, 2019 at 10:47 am

      I am truly greatful for your help. I looked everywhere just to find a solution.

      Reply
  30. Richard says

    December 12, 2019 at 3:01 am

    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

    Reply
  31. Stephen says

    December 18, 2019 at 3:00 am

    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.

    Reply
    • Scott DeLuzio says

      December 18, 2019 at 10:46 am

      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 the data-src attribute. Either that or the data-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.

      Reply
  32. Lucas Almeida says

    March 13, 2020 at 9:36 am

    Thank you so much!
    It worked perfectly.

    Reply
  33. Cerdan says

    March 19, 2020 at 9:04 am

    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… 🙁

    Reply
  34. Lamia Salsabil says

    May 5, 2020 at 12:31 am

    Thank you so much. It worked perfectly.

    Reply
  35. Luis says

    May 30, 2020 at 12:30 pm

    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!

    Reply
  36. balvir says

    June 9, 2020 at 6:21 am

    Thank You Sir
    It Really Work. It is perfect.

    Reply
  37. Steve says

    July 21, 2020 at 5:20 am

    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

    Reply
    • Scott DeLuzio says

      July 21, 2020 at 11:04 am

      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.

      Reply
  38. bluedogranch says

    August 5, 2020 at 3:06 pm

    Hi Scott,
    Thanks, this works great for single embeds on a page. I’m looking at your August 15, 2018 response and the Javascript to support multiple videos, and I get a “SyntaxError: missing ) after argument list”. So there’s a missing ) I guess. Any ideas?
    Thanks!

    Reply
  39. Iyke says

    February 13, 2021 at 11:12 pm

    I tried to use the code you provided for the functions.php file When I placed in the functions section I got this syntax error Could you help me with what I am doing wrong? Thanks

    syntax error, unexpected ‘var’ (T_VAR)

    Reply
  40. Diseño Web Zaragoza says

    July 31, 2021 at 8:53 am

    Great post! It has worked for me and helped me a lot when designing a website professionally. Congratulations for the article

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Come say hi!

  • Facebook
  • GitHub
  • Instagram
  • LinkedIn
  • Twitter
  • YouTube

Tweets by scottdeluzio

My Products

Conditional Checkout FieldsFull Screen Background ImagesQuick CheckoutWP1099

I use affiliate links throughout this site and may earn a commission if you purchase through my links. I do not link to products or services that I do not trust, or use myself.
© 2025 · Scott DeLuzio · Built on the Genesis Framework