JS: Deferred Loading JavaScript for Old Browser (2010)

By Xah Lee. Date: . Last updated: .

Problem

For older browser that doesn't support defer or async attributes , you can use JavaScript to insert a JavaScript by using document.createElement(), the newly inserted JavaScript will run after the HTML is loaded.

Suppose you want to use JavaScript to insert the following JavaScript code.

alert("yes");

Solution. Dynamically Create Script Tag on the Fly.

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);
var xx = document.createElement("script");
xx.innerHTML = 'alert("yes");'
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.

// 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);

window.onload

An old way to load script (used before ~2010), is to use the window.onload event.

This is not a good solution, because it waits until all images and iframes finished downloading too.

You'll see old code like this:

function f1 () {console.log( "f1 called");};
function f2 () {console.log( "f2 called");};

window.onload = function(){
    f1();
    f2();
};

Execution Order of Loading JS in HTML