JavaScript: Deferred Loading JavaScript for Old Browser
For older browser that doesn't support
defer
or
async
attributes
[see JavaScript: Load Order, defer, async, module]
, you can
use JavaScript to insert a JavaScript by using
document.createElement()
, the newly inserted JavaScript
will run after the DOM is ready.
Problem
Suppose you want to use JavaScript to insert the following JavaScript code.
alert("yes");
Solution 1
use JavaScript to create the script
element, then insert this node into DOM.
var xx = document.createElement("script"); xx.innerHTML = 'alert("yes");' document.body.appendChild(xx);
Solution 2
save the code in a file
xyz.js
,
then
use JavaScript to create the script
element, then insert this node into DOM.
var xx = document.createElement("script"); xx.src = "xyz.js"; document.body.appendChild(xx);
Creating Script Tag by InnerHTML Does Not Eval the JavaScript Code
If you add the script tag by using innerHTML, it does not work.
- As of , it fails in Firefox.
- As of , it fails in Google Chrome, Firefox.
// create new div element var xx = document.createElement("div"); // create script tag as div's content xx.innerHTML='<script>alert("yes");</script>'; // add to DOM document.body.appendChild(xx);