March 21, 2016

Defer iframe for your website to make your website loading fast

Defer iframe for your website to make your website loading fast. iframe source loading took some time and which blocks other scripts to load  as quickly as you can. We can defer the iframe so the other scripts can load quickly and our iframe will be loading after page scripts is fully loaded.

This method make the site faster.

This is default iframe user with no defer

<iframe width=”1280″ height=”720″ src=”https://www.youtube.com/embed/UYTpYxJ9K4Y?list=PL4oON97FJp1EA9bGxoG5l2V2vizelKLC2″ frameborder=”0″ allowfullscreen></iframe>

How to make defer in ifarame?

Just put the ‘src’  attribute blank and add the source url at  ‘data-src’ attribute.

<iframe width=”1280″ height=”720″ src=”” data-src=”https://www.youtube.com/embed/UYTpYxJ9K4Y?list=PL4oON97FJp1EA9bGxoG5l2V2vizelKLC2″ frameborder=”0″ allowfullscreen></iframe>

this is how we will not be loading iframe content during page load time. Now we have an script to replace the data-src attribute to the src attribute value. Put this code in your project.

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

Thats it.

You can test your website in GTMETRIX

You may also like...

Leave a Reply