Sometimes, we want to insert scripts with JavaScript.
In this article, we’ll look at how to insert scripts with JavaScript.
How to insert scripts with JavaScript?
To insert scripts with JavaScript, we use the createElement
method.
For instance, we write
const newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);
to create the script element with createElement
.
Then we set the script’s src
attribute by setting its src
property.
And then we call appendChild
to append the script element as the last child of the target
element.
Conclusion
To insert scripts with JavaScript, we use the createElement
method.