How to Add Script Tag to HTML DOM from JavaScript

Published Jul 1, 2022  ∙  Updated Aug 6, 2022

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 = "";
script.async = true;
// Step 3

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