Create a Script element using JavaScript


Borislav Hadzhiev

Fri Jan 07 20222 min read


Photo by Montse Monmo

Create a Script element using JavaScript #

To create a script element:

  1. Use the document.createElement() method to create the script element.
  2. Set the src attribute on the element to a local or remote JavaScript file.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples in this article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

const script = document.createElement('script'); // 👇️ local file // script.setAttribute('src', 'another-file.js'); // 👇️ remote file script.setAttribute( 'src', '', ); script.setAttribute('async', ''); // 👇️ optionally set script to be treated as JS module // script.setAttribute('type', 'module'); script.onload = function handleScriptLoaded() { console.log('script has loaded'); document.getElementById('box').textContent = 'Script loaded successfully'; }; script.onerror = function handleScriptError() { console.log('error loading script'); }; document.head.appendChild(script);

We used the document.createElement method to create the script element.

The only parameter we passed to the method is the type of element to be created.

The createElement method returns the newly created element.

We used the setAttribute method to set multiple attributes on the element.

The setAttribute method takes 2 parameters:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.
If the attribute already exists on the element, the value is updated, otherwise a new attribute is added with the specified name and value.

We set the script's src attribute to a remote JavaScript file, however you could set this to a path pointing to a file on your local file system.

We set the script's async attribute. When the async attribute is present, the script gets fetched in parallel to parsing and it gets evaluated as soon as it is available.

You can optionally set the script's type attribute to module if you are using JavaScript modules.

We added the onload event handler on the element.

The load event fires when the script has loaded successfully.

You can also add the onerror event on the element. The event fires when the script fails to load.

Note - you don't have to add these event handlers if you don't need to invoke a function when the script is loaded / fails to load.

There are many other attributes you might need to set on the script element depending on your use case. Here is a complete list from the MDN script docs.

If I load the example from the article in my browser, I can see that the script successfully loads on my page.

script created successfully

Use the search field on my Home Page to filter through my more than 1,000 articles.