JavaScript Execution Order

By Xah Lee. Date: . Last updated: .

This page shows the basics of JavaScript execution order, and techniques to run JavaScript deferred or asynchronous.

js async defer
JavaScript fetch and execute order for “normal”, and defer, async.

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.

HTML async / defer Attributes

In HTML5, you can tell browser when to run your JavaScript code. There are 2 new possibilities:

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

With defer, browser will run your script when the page finished parsing. (images may not have finished loading yet.)

With async (asynchronous), browser will continue loading the HTML page and render it while the browser load and execute the script at the same time.

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. This is so to support older browsers that doesn't support async.

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>.

As of , all major browser support async.

Multiple async scripts's execution order

Multiple async scripts's execution order is not guaranteed.

Multiple defer scripts's execution order

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

Deferred Loading JavaScript for Old Browser

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

Reference

HTML Standard#attr-script-async

Web Scripting Overview Topic

  1. JavaScript: Browser Window Object, Document Object Model
  2. JavaScript: Intro to Event-Based Programing
  3. JavaScript Execution Order
  4. JavaScript: What Does Live Object Mean?
  5. JavaScript: Array vs NodeList vs HTMLCollection
  6. JavaScript: DOM Whitespace Nodes
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.