mercredi 29 septembre 2021

How to run a JavaScript snippet only if an iframe exists on the current page?

I want to do a modification to YouTube embedded iframes to improve the Lighthouse score but I cannot make the if statement work:

if (document.getElementsByTagName('iframe')){
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;
    function parseJSAtOnload() {
        var element = document.createElement("script");
        element.src = "https://www.youtube-nocookie.com/yts/jsbin/player_ias-vflRCamp0/en_US/base.js";
        document.body.appendChild(element);
        }
        if (window.addEventListener)
            window.addEventListener("load", parseJSAtOnload, false);
        else if (window.attachEvent)
            window.attachEvent("onload", parseJSAtOnload);
        else window.onload = parseJSAtOnload;
}

I only want to run this snippet if there exists an iframe element on the current page and not always. This way I could embed the code on every page of my website, no matter of the content. With the above code it still gets active always. How to make it work only on pages with an iframe?

Aucun commentaire:

Enregistrer un commentaire