How to Create a Script Element in JavaScript?

Quick tip of the day, in this post we will see how to add a script to the page head dynamically.

For example, at danyal.dk I am not using moment.js library, and in order to present hot to add a js library dynamically to the HTML.

Consider the following HTML markup: index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body>
    <div id="box"></div>

    <script src="app.js"></script>
  </body>
</html>

Hereโ€™s how we can use JavaScript to create a script element in the HTML:

  • Use the document.createElement() method to create the script element.
  • Set the src attribute on the element object to a script file.
  • By setting the async property to true, the browser wonโ€™t have to load and evaluate the script before continuing to parse the HTML. Instead, the script file will be loaded in parallel to reduce delays and speed up the processing of the page.
  • Our page listens for the onload event in order to perform an action when the script file has been loaded successfully.
  • Our page also listens for the onerror event so that we can perform a different action in case there was an error with loading the script.
  • Include the script element in the HTML using the appendChild() method.

app.js

const script = document.createElement('script');

script.src =
  'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js';

script.async = true;


script.onload = () => {
  console.log('moment.js script is loaded successfuly');
  console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
};

script.onerror = () => {
  console.log('Error occurred while loading script');
};

document.body.appendChild(script);

Script execution in browser console & outcome

That’s how you can add a javascript remote or local script to the HTML DOM.
Cheers, see you in the next post!

Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.