Wednesday, March 26, 2008

Triggering Events on page load (and right before)

  1. Use prototype.js in your page.

  2. Call the Prototype function Event.observe() for the 'load' event. You can call the Event.observe() function as many times as you want, it will simply append your code each time, so as not to clobber each other when the event is fired. There are two ways you might perform this call. If you have a function you want to run, simply call:

    Event.observe(window, 'load', yourFunctionName);

    If you have a bit of code you want to run, call this instead:

    Event.observe(window, 'load', function() {
    // your bit of code here
    });
Do you want it to run onLoad... or onDOMLoad?

One important thing to realize is that the 'load' event for a page only fires AFTER all images on the page have been loaded. This may take a while, depending on your page design. You may be thinking that you will just run your bit of code when the page first starts loading. The problem with that is the DOM is not completely available yet, so your code will usually fail.

This guy has some javascript code that allows you to basically "observe" the onDOMLoad event, even in browsers that don't really export such an event. If you use his code to attach code to this event, it will run after the DOM is available, but before the "onload" event is fired for the page body.

The downside is it doesn't use prototype.js, so it may actually overlap a bit of that functionality. However, as of Prototype.js 1.6, their site was actually pointing to people to this guy's examples, so presumably that means there is no current expectation that Prototype does or will offer similar functionality.