JS: 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's a sample JavaScript code:

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

Test your browser: js_insert_js_works.html

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
document .body.appendChild(xx);

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

Test your browsor: js_insert_js.html

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog