Dynamically Create a Script Element with JavaScript

Hero image for Dynamically Create a Script Element with JavaScript. Image by Blake Connally.
Hero image for 'Dynamically Create a Script Element with JavaScript.' Image by Blake Connally.

This Article is Over Ten Years Old...

Things can and do move very quickly in tech, which means that tech-related articles go out of date almost as soon as they have been written and published. If you are looking for up-to-date technical advice or opinion, it is unlikely that you will find it on this page.

You may find that my recent articles are more relevant, and you are always welcome to drop me a line if you have a specific technical problem you are trying to solve.

There are many reasons why you might want to dynamically inject a <script> tag into your document from the client side. Here, I very briefly discuss how we can use the document.createElement() method, creating a new element and then setting its src attribute to the URL of the script we want to load. Finally, we can append the newlygenerated element to the HTML page via either document.head or document.body.

For example, let's say we want to load the script example.js and add it to the head of the HTML page. The code would look something like this:

var script = document.createElement('script');script.src = 'example.js';document.head.appendChild(script);

The resulting markup would look like this:

<script src="example.js" />

It really is that simple. Naturally, you're going to want to use some sort of document load detection to make sure that the document has actually loaded before initiating the dynamic injection.

You can also set innerHTML of the script element, rather than using an external file via src. This allows you to dynamically inject rudimentary JavaScript code into the head of your page.

var script = document.createElement('script');script.innerHTML = "console.log('example')";document.head.appendChild(script);//=> 'example'

This generates an element in the head that looks like this (and which will run immediately):

<script>  console.log('example');</script>

..and that is as simple as it gets!


Categories:

  1. Front‑End Development
  2. JavaScript