MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

JavaScript Execution Order; HTML5 Asynchronous JavaScript

Xah Lee, ,

This page explains the execution order of JavaScript in a HTML page, and answers some common questions.

When a JavaScript appears in a HTML page (either as a file or embeded code), the browser will load (and run) them in the order they appear on the HTML page.

This means:

So, the best solution is to always place your JavaScript at the bottom of the page, right before the </body> tag.

Onload: Wait for The Whole Page to Load

If for some reason you must have your script at the top of a HTML page, and your script need to see the whole page before it runs, then, here's trick to make sure your script runs only after the page has been loaded.

Use the “onload” method. Like this:

// function definitions here
function f1 () {…}
function f2 () {…}
function f3 () {…}
…

window.onload = ‹function name›;

This will call the function named ‹function name› after the window has been loaded.

If you have multiple functions to call, you can do it like this:

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

Here's a test page: JavaScript test page for onload. (view source to see code)

See also: Functional Programing in JavaScript.

Warning: “onload” will wait for everything

“onload” is not a good solution because it waits for the entire page to load, including all image files.

HTML5 “async” Feature

In HTML5, there's a “async” feature. You use it like this:

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

When the “async” attribute is present, it tell the browser not to wait for the script to load and finish execution. (The browser will continue to load the HTML page and render it while the browser load and execute the script.)

Note: The “async” should not be used with =true or =false. The presence of “async” attribute is enough.

There's also a “defer” attribute. When “defer” is present (and when “async” is not there), then browser will make sure that the script runs only after the HTML page is loaded.

Here's the official spec from whatwg.org. Quote:

The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes must not be specified if the src attribute is not present.

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

As of 2010-10, it seems only Firefox 3.6 supports “async”.

blog comments powered by Disqus