JavaScript: Deferred Loading JavaScript for Old Browser

By Xah Lee. Date: . Last updated: .

How to make JavaScript run Asynchronously?

Use async or defer attribute of the script tag. (supported by all major browsers since about )

<script async src="file.js"></script>
<script defer src="file.js"></script>

[see JavaScript Load Order]

Deferred Loading JavaScript for Old Browsers

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 DOM is ready.

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


Solution: use JavaScript to create the script element and its contents, then insert this node into DOM.

Here is a sample JavaScript code:

var ele = document.createElement("script");
ele.src = "xyz.js";

Putting Script Tag in innerHTML Does Not Work

Suppose you do it this way:

// create new div element
var xx = document.createElement("div");

// create script tag as div's content

// add to DOM

As of , it will fail in Google Chrome, Firefox.

JavaScript in Depth