Clue Mediator

How to dynamically load script with callback in JavaScript

📅June 5, 2020

Today we’ll show you how to dynamically load a script with callback in JavaScript. In this article, we will give you two different methods to load script text and load script by url in JavaScript. You can use the same method to dynamically load a script in ReactJS.

Dynamically load a script URL

Use the following code to dynamically load a script by URL.

function loadScriptByURL(id, url, callback) {
  const isScriptExist = document.getElementById(id);

  if (!isScriptExist) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    script.id = id;
    script.onload = function () {
      if (callback) callback();
    };
    document.body.appendChild(script);
  }

  if (isScriptExist && callback) callback();
}

// load the script by passing the URL
loadScriptByURL("script-id", "<path_of_script_url>", function () {
  console.log("Script URL loaded!");
});</path_of_script_url>

In the above code, we have asked to pass the three parameters as `id`, `url` and `callback` function.

In the function, we will check if the script exists in the dom then execute the `callback` function. If it’s not exist in the dom then load it by creating the script element and append it in body.

Dynamically load a script text

Use the following command where you can load the script text dynamically.

function loadScript(scriptText) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.innerHTML = scriptText;
  document.body.appendChild(script);
}

// load script text
loadScript(`
console.log('Script text loaded!');
console.log('This is second console.');
`);

In the above function, we have to pass the script text to dynamically to load in the document using `innerHTML`. Here we can’t check the script's existence in the dom.

That’s it for today.
Thank you for reading. Happy Coding..!!