Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 ) {
//...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!