PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 15, 2022

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

 April 15, 2022     if-statement, iframe, javascript, youtube     No comments   

Issue

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


Solution

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 ) {
//...


Answered By - Michael G
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing