💵
Should I be buying I-Bonds in 2022?
Should I be buying I-Bonds in 2022?
💰
Need a step-by-step guide to opening your Roth IRA?
Need a step-by-step guide to opening your Roth IRA?
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.
- 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)
.