How to prevent YouTube js calls from slowing down page load

Genadinik picture Genadinik · May 18, 2018 · Viewed 22.9k times · Source

I am using https://gtmetrix.com to diagnose issues with my page speed.

The page in question has one embedded YouTube video and GTMetrix is saying that this video's JS calls are slowing down page load speed.

This is the call being made:

<iframe width="640" height="360" src="https://www.youtube.com/embed/PgcokT0AWHo" frameborder="0" allowfullscreen></iframe>

Answer

Kaddath picture Kaddath · May 18, 2018

EDIT: as of October 2019, this is not working anymore (Thanks to @CpnCrunch for the update). For the cases where it's not impacting the user experience, you can apparently add a 1000ms timeout after the page load for it to take effect.

This is an example of attibuting the src dynamically on page load, using a pure JS solution. Using event listeners instead of window.onload because with the latter, only one event can be set and it would override any precedent window.onload event:

<iframe id="videoFrame" width="640" height="360" src="" frameborder="0" allowfullscreen></iframe>
<script>
function setVideoFrame(){
  document.getElementById('videoFrame').src = 'http://example.com/';
}
if (window.addEventListener)  // W3C DOM
  window.addEventListener('load', setVideoFrame, false);
else if (window.attachEvent) { // IE DOM
  window.attachEvent('onload', setVideoFrame);
}else{ //NO SUPPORT, lauching right now
  setVideoFrame();
}
</script>

Note that the script can be anywhere in the code, but in case of no support for event listeners (which is highly unlikely with nowadays browsers), the function is launched right away, so it should be at least after the iframe element.