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.
- Create
<script>
tag - Set element attributes
- 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 withdocument.head.appendChild(script)
.