Code Premix

Load script dynamically and add the callback in JavaScript

📅August 11, 2021|🗁JavaScript

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.

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!");
});

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..!!