HTML, Tutorials

How to defer videos from Youtube, Vimeo, etc.

12 February 2018

Why Should we defer videos?

When you put videos from Youtube, Vimeo, etc. it will take more time to load the page. Even if the video is in pop up section. And as per analysis if the loading time is greater than 4 seconds than there is 90% of chance that the visitor will leave your site. So to make your site load faster we need to defer video from YouTube, Vimeo and other websites.

How to defer videos

Here is sample code

<iframe width="560" height="315" src="https://www.youtube.com/embed/BGc_S-AQfEQ" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

1. The first change is replace “src” with “data-src”

So the video embedded code will be as below

<iframe width="560" height="315" data-src="https://www.youtube.com/embed/BGc_S-AQfEQ" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

2. Put the below code in Footer of the site

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

For most pages simply put the script right before the end body tag in your HTML.

Leave a Comments