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

Time:09-29

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?

I see this error in the developer console on all pages, even for ones without without any iframe elements:

GET https://www.youtube-nocookie.com/yts/jsbin/player_ias-vflRCamp0/en_US/base.js net::ERR_ABORTED 404

CodePudding user response:

document.getElementsByTagName() returns an empty collection.
Empty HTMLCollections are objects, which reduce to the primitive true. (I know, JavaScript is crazy...)

So, if( document.getElementsByTagName( 'no-such-element' ) ) will always evaluate to true.

You want:

if( document.getElementsByTagName( 'iframe' ).length > 0 ) {
//...
  • Related