Conditionally load a JavaScript file

OpenJavaScript 0

Last updated: December 17, 2022.

You may not want a JavaScript file to always load in the browser. Instead, you can make it load conditionally upon something being true (e.g. user location, browser compatibility).

There are two ways to make script loading conditional: dynamically creating and adding a script or replicating an existing script.

Creating and adding a script dynamically

This method involves creating a new script element and then appending it to the DOM.

As soon as the script hits the DOM, it will start loading:

const condition = Math.floor((Math.random()*2))
// 50% probability that condition equals 1

if (condition === 1) {

  const script = document.createElement('script');

  script.src = './script.js'; // Path to script

  script.type = 'text/javascript';

  document.body.appendChild(script);
  // Script runs as soon as it is appended

}

If you want to load multiple scripts conditionally, you can store the path to each script in an array and then iterate through it, setting the path to src each time:

const condition = Math.floor((Math.random()*2));

const scripts = ['./script2.js', './script3.js'];
// Scripts paths are now stored in an array

if (condition === 1) {

  scripts.forEach((item) => {
    
    const script = document.createElement('script');

    script.src = item;
    // src is now set each time to current array item

    script.type = 'text/javascript';

    script.async = false; 
    // Prevents async loading behavior

    document.body.appendChild(script);

  });

}

Note that if not otherwise specified, a script inserted by JavaScript will load with async behavior by default. This means that there is no guarentee that scripts will execute in the order they are appended.

If you want scripts to load in a guarenteed order, set an async attribute value to false.

Replicate and append existings (conditioanal) scripts

This method allows you to include scripts you want to be conditional in your initial markup.

The trick is to initially set the type attribute of a script to plain/text. With this, the script will be ignored by the browser.

Also, in order that you can select scripts you want to load conditionally in JavaScript, add an identifiable class attribute value for each script (conditional in the code below).

When you want conditional scripts to run, create a new script for each conditional script in JavaScript. Set the attributes of each new script those of each conditional script.

Then append each new script to the DOM, causing them to run:

<script src="script.js" type="text/javascript"></script>
<script src="script2.js" class="conditional" type="text/plain"></script>
<script src="script3.js" class="conditional" type="text/plain"></script>

<script>

const condition = Math.floor((Math.random()*2));

if (condition === 1) {

  const cScripts = document.querySelectorAll('.conditional');

  cScripts.forEach((item) => {

    const script = document.createElement('script');

    const attrs = item.getAttributeNames();

    attrs.forEach((attr) => {

      script.setAttribute(attr, item.getAttribute(attr));

    });

    script.type = 'text/javascript';

    script.async = false;

    item.remove();
    document.head.appendChild(script);

  })

}

</script>

Related posts