3 Ways To Dynamically Load Javascript (Simple Examples)

Welcome to a quick tutorial on how to dynamically load Javascript. So you want to build a single-page web app that requires some magic to load more scripts only after the user has clicked on something?

To load an external Javascript file dynamically, we can create a <script> tag and insert it into the head section.

  • var js = document.createElement("script");
  • js.src = "SCRIPT.JS";
  • document.head.appendChild(js);

That covers the quick basics, but let us walk through a few more examples in this guide – Read on!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/dynamically-load-javascrip/” title=”How To Dynamically Load Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

DYNAMICALLY LOAD JAVASCRIPT

All right, let us now get into the various examples of dynamically loading Javascript with Javascript.

 

1) CREATE A NEW SCRIPT TAG

1a-load-js.html
<!-- (A) TEST BUTTON -->
<input type="button" onclick="demo()" value="Demo">
<input type="button" onclick="loadjs()" value="Load JS">
 
<!-- (B) DYNAMICALLY LOAD JS -->
<script>
function loadjs () {
  // (B1) CREATE NEW <SCRIPT> TAG
  var js = document.createElement("script");
  js.src = "1b-demo.js";
  // js.setAttribute("async", "");
 
  // (B2) OPTIONAL - ON SUCCESSFUL LOAD & ERROR
  js.onload = () => alert("JS loaded");
  js.onerror = e => alert("Error loading JS");
 
  // (B3) APPEND <SCRIPT> TAG TO <HEAD>
  document.head.appendChild(js);
}
</script>
1b-test.js
function demo () {
  alert("It Works!");
}

As in the above introduction, loading an external Javascript file is as easy as creating a new <script> tag and insert it into <head>. But take note of the extra onload and onerror listeners here – Use these to help you better manage your app, proceed only when the script is fully loaded.

 

 

2) USE JAVASCRIPT TO GENERATE JAVASCRIPT

2-insert-js.html
<!-- (A) TEST BUTTON -->
<input type="button" onclick="demo()" value="Demo">
<input type="button" onclick="loadjs()" value="Create JS">
 
 <!-- (B) DYNAMICALLY CREATE JS -->
<script>
function loadjs () {
  // (B1) CREATE NEW <SCRIPT> TAG
  var js = document.createElement("script");
  js.textContent = `function demo () { alert("It works!"); }`;
 
  // (B2) INSERT <SCRIPT> TAG TO <HEAD>
  document.head.appendChild(js);
  alert("JS Inserted");
}
</script>

Here’s the “top secret”, we don’t actually need to load a Javascript file. Yes, Javascript is an interpreted language. We only need to create the <script> tag, enter some Javascript, and insert it into the HTML page… The browser will do the rest.

 

3) AJAX LOAD JAVASCRIPT FILE

3-ajax-js.html
<!-- (A) TEST BUTTON -->
<input type="button" onclick="demo()" value="Demo">
<input type="button" onclick="loadjs()" value="Load JS">

<!-- (B) DYNAMICALLY LOAD JS -->
<script>
function loadjs () {
  // (B1) AJAX LOAD
  fetch("1b-demo.js")
  .then(res => res.text())
  .then(txt => {
    // (B2) CREATE NEW <SCRIPT> TAG
    var js = document.createElement("script");
    js.textContent = txt;
 
    // (B3) APPEND <SCRIPT> TAG TO <HEAD>
    document.head.appendChild(js);
    alert("JS Loaded");
  });
}
</script>

Lastly, we have sort of a negative example. For you guys who are thinking along the lines of “load Javascript asynchronously” – Yes, this works, we can use AJAX to load a Javascript file.

But in modern Javascript, this is a roundabout way to do things. Refer back to the first example, just create a <script async src="FILE.JS">. That does the equivalent of “load Javascript asynchronously”.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

DEFER LOADING JAVASCRIPT

If you only want to delay the loading of a Javascript file, just use <script defer>. The browser will automatically defer loading the script until the entire page is ready. No need to do any of these “loading gimmicks”.

 

UNLOADING JAVASCRIPT

Yes, we can dynamically load more Javascript files. But at the time of writing, there don’t seem to have any smart ways to “unload Javascript files”. Loading more and more Javascript files is not the solution to massive web apps. Finding ways to simplify and standardize is.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Dynamically Load JS Files

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!