JS: Load Order

By Xah Lee. Date: . Last updated: .

When a JavaScript appears in a HTML page:

<script src="…"></script>

or

<script>…</script>

the browser will fetch and execute the script right away, and wait for it to finish, before loading any HTML that appear after the script tag.

This means:

Old solution (2005) is to always place your JavaScript at the bottom of the page, right before the </body> tag. But this is not a good solution today.

defer Load

You can use the attribute defer like this:

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

defer means run script after the page finished parsing.

Warning: there's no “=true” or “=false” after async or defer.

Warning: When using defer or async, you must have a src="…". You cannot use it like this: <script defer>…</script>. That'll behave the same as without defer/async.

As of , all major browser support defer.

Multiple defer scripts's execution order is by the order they appear on HTML page.

async Load

async (asynchronous) means run the script and continue loading the HTML page at the same time.

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

Warning: with async, your script will not see HTML elements that are below the script tag, because they are not loaded yet.

If both async and defer are specified, it behaves as if only defer is specified.

Multiple async scripts's execution order is not guaranteed.

As of , all major browser support async.

Module Script Load Order

When type="module" script is used, it loads like defer.

Optionally you can specify async loading.

[see JS: Import/Export]

js async defer 6hhq9
JavaScript fetch and execute order [image source whatwg.org , © https://creativecommons.org/licenses/by/4.0/legalcode ]

Deferred Loading JavaScript for Old Browser

JS: Deferred Loading JavaScript for Old Browser

Load Event: Wait for the Whole Page to Load

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();
};

DOM How-To


Web Scripting Overview


HTML Input


Web Scripting Examples


Web Scripting Misc


jQuery


node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials