Site hosted by Angelfire.com: Build your free website today!

Avoiding Javascript Race Conditions

Introduction

Why the race happens

Why onload events don't work

Some programmers write the code that refers to functions or objects that might not have loaded in routines that are called via the onload event of a BODY tag. This is NOT a good approach. Here's why it doesn't work, and what can go wrong (here by primary page I mean the page the user has requested, and not the other pages that the browser loads because they are referenced from it):
  1. The BODY onload event fires too soon. It fires when the text of the primary page has loaded into memory, not when it has been parsed (that is, interpreted by the browser) in its entirety.
  2. Anything loading via references from the primary page might not have finished yet.
  3. Worse, functions or objects defined near the end of the page may not have been fully parsed yet. The Netscape parser seems slower, and over a fast connection, you will sometimes see the onload event failing because it refers to a function which, although it has been loaded, the browser hasn't looked at yet. So it says there's no such function, even though there is.
  4. If you use an onload event, and put the function definition in the <HEAD> part of the document, you can at least expect that the browser will "find" your onload function. But you cannot be sure that anything it refers to will actually have been parsed.
It's also possible, in IE, to write code that relies on document state changes to tell it when the page has fully loaded. But not only isn't it portable once you do that, it isn't reliable either. It can tell you that a page and all the things it depends on are fully loaded, and be wrong. Particularly for framesets, where it tells you only if your document's children are loaded (mostly...). Not if your document's children's children are loaded.

Why putting your javascript code last still might not work

The solution