Javascript, Tutorials

Defer Parsing of JavaScript With YouTube Videos

19 July 2018

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

1. Replace “src” with “data-src”

In your Iframe you will see “src” tag. We need to replace that tag with “data-src” tag. So if your YouTube iframe will look like this.

<iframe width="560" height="315" data-src="https://www.youtube.com/embed/123456789" frameborder="0" allowfullscreen></iframe>

2. Add Javascript

It’s still not done yet. Put below JavaScript in footer part of HTML before closing the Body tag.

function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
} } }
window.onload = init();

Now Enjoy your site’s lightening speed.

Leave a Comments