How to Add Script Tag to HTML DOM from JavaScript


How can we add a script tag to the HTML DOM from JavaScript?

In my case, I needed to conditionally inject a script tag into the DOM.

This only requires a few steps.

  1. Create <script> tag
  2. Set element attributes
  3. Append tag to the DOM
// Step 1
const script = document.createElement("script");
// Step 2
script.src = "https://some-script-url.com";
script.async = true;
// Step 3
document.body.appendChild(script);

You can append to the <head> just as easily with document.head.appendChild(script).