Document Ready and Loaded Events with prototype.js

11. September 2008 18:07

Okay, I was playing around with the DOM Ready vs Window Load events with prototype.js and noticed that in my simple example, the window event actually fired before the dom event in IE8.  This could lead to some issues, especially on cached pages, so I wanted to make a note of it.  Why is it even an issue? Well, using the DOM ready event will allow you to hide things as soon as the tree has it. Using the window loaded event is necessary in order to handle flowing layouts in terms of size/proportion.

Object.extend(document, {
    isDocReady: false,
    isDocLoaded: false,
    ready: function(fn) { Event.observe(document, "doc:ready", fn); },
    load: function(fn) { Event.observe(document, "doc:loaded", fn); }
Event.observe(document, "dom:loaded", function() {, "doc:ready");
    document.isDocReady = true;
    if (document.isDocLoaded), "doc:loaded");
Event.observe(window, "load", function() {
    document.isDocLoaded = true;
    if (!document.isDocReady) return;, "doc:loaded");

The above establishes some custom events for the document object, and creates listeners that will assure that they fire in the correct order... this way I can subscribe to the new events, directly, or through the jQuery-style methods...

document.observe("doc:ready", function(){
document.observe("doc:loaded", function(){
document.ready(function(){ alert("Ready Too!"); });
document.load(function(){ alert("Loaded Too!"); });

Much nicer being able to have both available, with a guarantee they fire in the expected oerder.

Updated 2009-06-22: combined with the prior post.


Comments are closed


Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.