Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 74735

How do I load a JavaScript resource conditionally based on the presence of a certain ID tag in a page's HTML file?

$
0
0

Situation

In a web application I'm helping maintain, a change is specified wherein a certain JavaScript script must load conditionally, depending on the presence or absence of a certain element ID on the page.

Question

How best to achieve this result without external libraries and in a manner consistent with current accepted practice?

Current approach idea

My thought at present is to do something like the following; I'd appreciate some guidance, including in re : whether this approach is advisable and / or better alternative methods.

// identify head of html 
const htmlHead = document.querySelector('head');

// identify desired change condition and assign 
const desiredIdPresent = document.querySelector('#foo');

// assign script creation      
const activeScript = document.createElement('script');
      activeScript.type = 'text/javascript';


// conditions determine which script loads
if (desiredIdPresent){
    activeScript.src =  '/foo.js';
} else {
    activeScript.src = '/bar.js';
};

// insert desired script into document head
htmlHead.appendChild(activeScript);

there are some somewhat similar situations and solutions in the following, which among others I've also used as reference:

conditionally load javascript resource

Conditionally load JavaScript file


Viewing all articles
Browse latest Browse all 74735

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>