How to Add Script Tag to HTML DOM

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

I needed to 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

Here’s the code:

// Step 1
const script = document.createElement("script");
// Step 2
script.src = "https://the-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).


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *