JavaScript window.onload Scheduler

JavaScript programmers often use the window.onload property to execute code when a document has loaded. This causes problems for programmers making use of several pieces of JavaScript code which set the window.onload property. While the use of addEventListener (or attachEvent in Internet Explorer) allows multiple functions to be executed when the document has loaded, older browsers do not support these functions. OnloadScheduler solves these problems, and allows more advanced scheduling through setting task priorities.

OnloadScheduler

FileSizeDescription
OnloadScheduler.js1605 bytesFull version with comments
OnloadScheduler.compressed.js1046 bytesCompressed version

Download one of the files listed above and upload it to your website. Link to it from your page with code such as:

<script type="text/javascript" src="OnloadScheduler.js"></script>

When the OnloadScheduler object is created it sets window.onload to execute the scheduled events. Events may be scheduled at any time before the document has finished loading. Once the scheduled events have been executed, OnloadScheduler sets itself to null so that the garbage collector can reclaim the memory it had used.

Scheduling events

The simplest way of scheduling events is by calling the schedule function with a single parameter:

OnloadScheduler.schedule(someFunction);
OnloadScheduler.schedule('someCode');

The schedule function can take a string as a convenience — it will wrap the specified code in an anonymous function and then call the schedule function again with this anonymous function as a parameter.

Using priorities

OnloadScheduler defines priorities in a way similar to that in many operating systems. Priority level 0 is the default, and is used when no priority is specified (as shown in the examples above). Lower numbers represent higher priorities and higher numbers represent lower priorities — for example, a task at priority level -1 is of a higher priority than a task at priority level 1.

The schedule function can accept a second parameter specifying the priority:

OnloadScheduler.schedule(someFunction, priority);
OnloadScheduler.schedule('someCode', priority);

As example of the use of priorities, consider the following code:

OnloadScheduler.schedule('alert(\'A\')');
OnloadScheduler.schedule('alert(\'B\')', 1);
OnloadScheduler.schedule('alert(\'C\')', 0);
OnloadScheduler.schedule('alert(\'D\')', -1);

When the document loads, alert boxes will pop up with the messages D, A, C, and B. Firstly, D is displayed as it is at priority level -1. A and C are then displayed as they both are at priority level 0 — tasks at the same priority level are executed in the order in which they were scheduled. Finally, B is displayed as it is at priority level 1.

This article was last edited on 15th March 2008. The author can be contacted using the form below.
Back to home page
Bookmark with: