Ways to add javascript files dynamically in a page

Asked
Active3 hr before
Viewed126 times

9 Answers

javascript
90%

Load a css file dynamically

// Create new script elementconst script = document.createElement('script');script.src = '/path/to/js/file.js';
// Append to the `head` elementdocument.head.appendChild(script);
load more v
88%

To add a new javascript file dynamically:,I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.,Stack Overflow en español, Stack Overflow Public questions & answers

To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:

function loadjscssfile(filename, filetype) {
   if (filetype == "js") { //if filename is a external JavaScript file
      var fileref = document.createElement('script')
      fileref.setAttribute("type", "text/javascript")
      fileref.setAttribute("src", filename)
   } else if (filetype == "css") { //if filename is an external CSS file
      var fileref = document.createElement("link")
      fileref.setAttribute("rel", "stylesheet")
      fileref.setAttribute("type", "text/css")
      fileref.setAttribute("href", filename)
   }
   if (typeof fileref != "undefined")
      document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
load more v
72%

If we modify our full example to load our external script file first, here is what the full HTML, CSS, and JS will look like:,There are two new things going on in the code that ensure our external script file is loaded and run before anything else on the page is rendered:, Learning React: A Hands-on Guide BUY ,If easing.js isn't showing up for you, refresh the page with the Network inspector tab open. That will ensure you can see the external script file being requested and then loaded.

In the Running Your Code at the Right Time time article, a part of what we looked at were the various ways we have to load and run external JavaScript files in our pages. All of these various ways assumed we knew exactly what script file we wanted to load with the src attribute already pointing to our file:

<script src="https://www.example.com/foo.js"></script>
load more v
65%

I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.,To add a new javascript file dynamically:,For example, I would like to include my js files like,,You can use the jQuery.getScript() function... I think it will be much easier to you with this to include a JavaScript .js file.

For example, I would like to include my js files like,

<script src="single.js?files=first.js,second.js,third.js..."></script>
load more v
75%

Today, we will have a look at different ways to dynamically load JavaScript files after the page is fully loaded.,Another way to dynamically load a JavaScript file is to retrieve it using a classic HTTP request. This is a pure JavaScript call, and yet it has many drawbacks.,https://github.com/elsheimy/Samples.DynamicLoadJavaScriptFile,The most straightforward way to load a JavaScript file is to reference it in an <script> element. The easiest way to dynamically load this file is to dynamically load this element! (You didn’t see that coming? Did you?)

Let us define our example model, we will start by defining the remote file that needs to be dynamically loaded. Here’s the definition for the “remote.js” file.

// this is going to be executed when script is loaded
(function() {
   console.log("Remote script loaded");
}());
var sayHello = function(name) {
   alert("Hello", name);
}
load more v
40%

The most straightforward way to load a JavaScript file is to reference it in a <script> element. The easiest way to dynamically load this file is to dynamically load this element! (You didn’t see that coming? Did you?),https://github.com/elsheimy/Samples.DynamicLoadJavaScriptFile,Another way to dynamically load a JavaScript file is to retrieve it using a classic HTTP request. This is a pure JavaScript call, and yet it has many drawbacks. Let us see it in action:,Now you can easily call require() along with JavaScript path and a callback function to be notified when the script is loaded.

// this is going to be executed when script is loaded
(function() {
   console.log("Remote script loaded");
}());

var sayHello = function(name) {
   alert("Hello", name);
}
<html>
<head>
</head>
<body>
  <button id="loadButton">Load script file</button>
  <script type="text/javascript">
    document.getElementById('loadButton').onclick = function () {
      // your code goes here
    };
  </script>
</body>
</html>
document.getElementById("loadButton").onclick = function() {
   var script = document.createElement("script");
   script.src = "remote.js";

   script.onload = function() {
      sayHello("Mohammad");
   };

   // append and execute script
   document.documentElement.firstChild.appendChild(script);
};
/**
 * Used to load and execute javascript file. an be used cross-domain seamlessly.
 * @param file JS file name
 * @param callback Subscribe to get notified when script file is loaded
 **/
function require(file, callback) {
   // create script element

   var script = document.createElement("script");
   script.src = file;

   // monitor script loading
   // IE < 7, does not support onload
   if (callback) {
      script.onreadystatechange = function() {
         if (script.readyState === "loaded" || script.readyState === "complete") {
            // no need to be notified again
            script.onreadystatechange = null;
            // notify user
            callback();
         }
      };

      // other browsers
      script.onload = function() {
         callback();
      };
   }

   // append and execute script
   document.documentElement.firstChild.appendChild(script);
}

document.getElementById("loadButton").onclick = function() {
   require("remote.js", function() {
      sayHello("Mohammad");
   });
};
/**
 * Used to load and execute javascript file. Suffers from same-domain restriction.
 * @param file JS file name
 * @param callback Subscribe to get notified when script file is loaded
 **/
function requireXhr(file, callback) {
   // object initialization
   const xhr = new XMLHttpRequest();

   // subscribe to request events
   xhr.onreadystatechange = function() {
      // readyState:
      // 0 UNSENT Client has been created. open() not called yet.
      // 1 OPENED open() has been called.
      // 2 HEADERS_RECEIVED send() has been called, and headers and status are available.
      // 3 LOADING Downloading; responseText holds partial data.
      // 4 DONE The operation is complete.

      // when not done, return
      if (xhr.readyState !== 4) {
         return;
      }

      // done, check status code
      if (xhr.status !== 200) // 200 = OK
      {
         return;
      }

      // now the file is loaded,
      // go and execute the script
      eval(xhr.responseText);

      // notify caller
      if (callback) {
         callback();
      }
   };

   // open connection to file
   xhr.open("GET", file, true);

   // send the request
   xhr.send();
}

document.getElementById("loadButton").onclick = function() {
   requireXhr("remote.js", function() {
      sayHello("Mohammad");
   });
};
/**
 * Used to load and execute JavaScript file. 
 * @param file JS file name
 * @param callback Subscribe to get notified when script file is loaded
 **/
function requireAjax(file, callback) {
   jQuery.getScript(file, callback);
}

document.getElementById("loadButton").onclick = function() {
   requireAjax("remote.js", function() {
      sayHello("Mohammad");
   });
};
load more v
22%

var newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);
load more v
60%

AWS certification career opportunities,Business Intelligence Masters Program,Implement Optical Character Recognition in Python,Apache Spark and Scala Certification Training

You can listen to the script's load event, and do things with the results as you would. So:

var script = document.createElement('script');
script.onload = function() {
   //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes
48%

For libraries that are only used in one or a few places, placing calls to load these libraries in our application's <head></head> can add unnecessary page load, and subsequently, load time.,For libraries that are used globally across the site, placing these in our main <head></head> is perfectly fine. ,When we're building single-page or JavaScript driven applications using tools like Pup, from time to time we need to rely on third-party libraries that require a script tag being placed in the <head></head> or <body></body> of our HTML. ,One last detail: notice the call to script.onload here? This is to give us control over loading elements in our UI that are dependent on the script existing. The callback argument passed to our loadGoogleMaps function here is designed to call some code after the library has loaded.

Dynamic Script Loading Template

const loadDynamicScript = (callback) => {
   const existingScript = document.getElementById('scriptId');

   if (!existingScript) {
      const script = document.createElement('script');
      script.src = 'url'; // URL for the third-party library being loaded.
      script.id = 'libraryName'; // e.g., googleMaps or stripe
      document.body.appendChild(script);

      script.onload = () => {
         if (callback) callback();
      };
   }

   if (existingScript && callback) callback();
};
load more v

Other "javascript-undefined" queries related to "Ways to add javascript files dynamically in a page"