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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

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

 

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *