jQuery, document.ready and the Prototype equivalent

Jquery has a handy way of allowing you to do stuff as soon as the document object model for a page has loaded (ie. as soon as the browser has loaded all your markup). I’m currently working on a project that requires Prototype JS, and I had some difficulty finding the equivalent method.. hence this post.

I knew Prototype had evolved somewhat since I’d last used it extensively back in late 2006, and I also suspected they had implemented something similar.. but Google was not forthcoming.

The traditional way to do this (pre jQuery) was to put your javascript directly before the closing body tag. This way the browser is unable to execute it prior to loading the rest of the page. However this is kind of clunky if you are trying to abstract your javascript to a linked file, or would like to keep your behavioral code (javascript) separate to your markup (xhtml).

An alternative is to use the onload event – in Prototype you would use something like Event.observe(window, 'load', function() { 
.. do stuff ..
});

The problem with this method is that obviously your users have to wait for all the document’s images and other content to finish loading before they can properly interact with the page. Most users aren’t that patient, and will try to use features that aren’t ready to be used, presenting them with a broken user experience.

Here’s the Prototype implementation of document.ready as explained by the Prototype JS website.

6 Responses to “jQuery, document.ready and the Prototype equivalent”

  1. Thanks! I was needing it. =)

  2. 2 Hours searching for this !

    Thanks thanks thanks !

  3. Thanks,I just want use prototypejs instead of jquery!!

  4. Well, just a year after you made this post I found the solution at prototype page; I put it here for future searches of people who wants a solution for this:

    http://www.prototypejs.org/api/document/observe

    Since version 1.6.0, now you have the option “dom:loaded” to use it with Event.observe:

    document.observe(“dom:loaded”, function() {
    // initially hide all containers for tab content
    $$(‘div.tabcontent’).invoke(‘hide’);
    });

    It will fire immediately after the HTML document is fully loaded, but before images on the page are fully loaded.

  5. Very helpful, thanks! I’ll be refactoring a lot this weekend. :)

  6. […] Alternatively, use prototype (which you already include)’s equivalent of document.ready. […]

Leave a Reply

Amatomu