Last updated: Mar 5, 2024
Reading timeยท2 min
To create a script element in JavaScript:
document.createElement()
method to create the script
element.src
attribute on the element to a local or remote JavaScript file.appendChild()
method.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', ); 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.
const script = document.createElement('script');
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:
name
- the name of the attribute whose value is to be set.value
- the value to assign to the attribute.const script = document.createElement('script'); // ๐๏ธ local file // script.setAttribute('src', 'another-file.js'); // ๐๏ธ remote file script.setAttribute( 'src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', ); script.setAttribute('async', '');
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 gets evaluated as soon as it
is available.
You can optionally set the script's type
attribute to module
if you use
JavaScript modules.
// ๐๏ธ optionally set script to be treated as JS module script.setAttribute('type', 'module');
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.
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.
You can learn more about the related topics by checking out the following tutorials: