How to Not Let YouTube iFrame Embed Affect Page Speed

Posted on: May 6th, 2024
By: Tadeo Martinez

This works perfectly because the iFrame won’t load until the user has clicked on the image (in this case).

I embedded the iFrame in the footer and that didn’t work. Doing it this way with the click event listener is the only way to not make an iFrame embed affect page speed.

<!-- Replace the iframe with an image thumbnail -->
<img src="" width="560" height="315" id="youtube-thumbnail" style="cursor: pointer;" />

// JavaScript to load the YouTube player when the thumbnail is clicked
document.getElementById('youtube-thumbnail').addEventListener('click', function() {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('width', '560');
    iframe.setAttribute('height', '315');
    iframe.setAttribute('src', '');
    iframe.setAttribute('frameborder', '0');
    iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
    iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
    iframe.setAttribute('allowfullscreen', '');
    // Replace the thumbnail with the YouTube player
    document.getElementById('youtube-thumbnail').parentNode.replaceChild(iframe, document.getElementById('youtube-thumbnail'));

Have any questions or comments? Write them below!

Leave a Reply

Your email address will not be published. Required fields are marked *