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.

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!