Home » Tutorials » JavaScript » Make Your Web Faster by Deferring Embedded Video

Make Your Web Faster by Deferring Embedded Video

Make Your Web Faster by Deferring Embedded Video

If you have embedded video from Youtube in your web pages it causes your page to load slower. Page loading speed is important for user experiences and your page ranking in Search Engine Result page.

Deferring embedded video in your web page to allows your page load quickly, saving dozens of files requests and resource downloads in your initial pageload.

Defer The Video

To defer the video, the first changes is to remove the URL in the “src” attribute, and adding 1 new attribute called – “data-src”.

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

The second change is to write a small chunk of JavaScript to tells browser to load the embedded video after the page loads. Then simply put the script right before the end body tag in your html.

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

Found it useful? Share it to your colleagues & communities!

Want to learn more Page Speed Optimization techniques?

  • pepe

    demo men

    • The code is there, please try and checkout the data / statistic yourself. 🙂 thanks.

    • pepe

      codepen.io ?. hhm well

  • using iframe and img defer at the same tioem doesn’t work, when using the above code it then breaks img lazy load

  • MarkCanada2015

    Try removing the ” src= ” attribute since it is empty anyway.The script will still work and it might validate.

    I say this because I use it in WordPress and with the theme I am using, it kept removing the empty ” src= ” attribute, leaving the rest and all worked fine.