When you want to run code when a page loads, usually you put an event handler on the window.onload event or the onload event of the body tag. The problem with that approach is that your code doesn't run until the page is fully loaded, including all of the images. Sometimes that's just not soon enough — there's code you want to run as soon as possible that doesn't care whether the images are loaded. For instance, perhaps you want to attach 'click' handlers to various UI elements (because you haven't cluttered up your HTML with onclick= statements). You could put in inline script tags, of course, but then you run the risk of trying to do things with the DOM (like find elements by their ID) before it's been loaded. What you want is an event that triggers when the DOM is loaded.
Using Prototype's dom:loaded event
Fortunately, Prototype provides just such an event: dom:loaded:
document.observe('dom:loaded', pageInit); function pageInit() { // This code runs as soon as possible once the DOM is available $('myButton').observe('click', buttonClickHandler); }
The dom:loaded event is fired as soon as the html code have been parsed and DOM tree created. All the the elements are accessible via their id attributes. This is very good moment to hide unneeded elements, attach events, or apply behaviors.
When not to use dom:loaded
The dom:loaded event shouldn't be used when dealing with dimensions or positions of elements. Prototype fires this event when all html code has been loaded, and DOM tree created. This does not meen the page was fully rendered. Dimensions and positions of elements might still change as the images are loaded and displayed. Also the widths of table columns can be still changed while the page is rendering. You should also note that dom:loaded is often used to hide elements (such as navigation submenus) at page load. This also can change position or dimensions of other elements.
When you need to position some elements on page load or set it's dimensions, you should use old good window.onload event. This guarantees that the page is rendered and all the elements' positions and dimensions already determined.
Using a script tag at the bottom of the document
Another technique is to put a script tag at the very end of the page to call your init function, ideally after a very brief delay:
<html> <head> <!-- ... --> <script type="text/javascript"> function pageInit() { // This code runs on page init $('myButton').observe('click', buttonClickHandler); } </script> </head> <body> <!-- ... --> <script type="text/javascript"> // Trigger our init code pageInit.defer(); </script> </body> </html>
That example uses the Prototype Function.defer method to defer execution of the function by just a tiny bit.