Defer parsing of JavaScript in GTmetrix results

I have added a youtube video embed to the home page on my website, which works great, However, when I analyse this page using with https://gtmetrix.com one of the issues I am seeing is error asking me to defer the leading of youtube video, to essentially load this iframe after all of my assets are finished loading.

Here’s what my initial code looked like:

<iframe width="680" height="383" src="https://www.youtube.com/embed/c_QLUv9FUHo?showinfo=0&amp;autoplay=0&amp;rel=0" frameborder="0" gesture="media" allowfullscreen=""></iframe>

and here is the issue being highlighted by gtmetrix:

gtmetrix defe youtube

I made a couple of changes to this code, namely adding an ID of “youtube”, and removing the src attribute, but adding a data-src attribute with the same value. Here’s my amended iframe code:

<iframeid="youtube" src="" data-src="https://www.youtube.com/embed/scDpX9nIUVU?showinfo=0&amp;autoplay=1&amp;rel=0"frameborder="0"gesture="media"allowfullscreen=""></iframe>

I then added a fewof lines of javascript at the bottom of my page.

functionvidDefer() {
varyoutubeDefer = document.getElementById('youtube');

youtubeDefer.setAttribute('src',youtubeDefer.getAttribute('data-src'));
}
window.onload = init;

I ran the gtmetrix test once more, and here is the result so it went from an F rating, to a B rating.

Please leave your comments below if this helped you.

Cheers,
Jamie

Leave a Reply

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