mardi 21 janvier 2020

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

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

Aucun commentaire:

Enregistrer un commentaire