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

Community
  • 1
  • 1
Mister October
  • 165
  • 1
  • 9

1 Answers1

1

The issue is due to the synchronous aspect of the loading of the page. Your code seems to be trying to search for #foo before it is loaded.

The solution : put your script tag at the end of your body. Example :

<body>
    <div id="foo"></div>

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

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

// 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);
    </script>
    <!-- OR --> <script src="k.js"/>
</body>

I have no touched one centimeter of your JS.

clota974
  • 495
  • 5
  • 16