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.

<script>
function videoLoad() {
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 = videoLoad;
</script> 

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

Android, iOS Development Tutorials