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

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

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

There are currently no comments.