DomReady Event Methods in JavaScript Frameworks

By  on  

The "domready" event, as it is affectionately known as, is one of the best things since sliced bread. The domready event says "screw you window.load ... I don't have time to wait for you." The ability to execute your JavaScript method on DOM nodes before the page loads helps to make our effects and element modifications that much more seamless. Every JavaScript framework has their own method of domready so I wanted to take the time to list off each one, just in case you (or I) need to work with a framework that's (initially) outside of our comfort zone.

MooTools (FTW)

window.addEvent('domready',function() {
	//do stuff
});

jQuery

jQuery(document).ready(function() {
	//do stuff
})

Dojo Toolkit

dojo.addOnLoad(function() {
	//do stuff
});

YUI

YUI().use('*',function(Y) {
	Y.on("domready", function() {
		//do stuff
	}, Y, "The DOMContentLoaded event fired.  The DOM is now safe to modify via script.");
});

Prototype

document.observe("dom:loaded", function() { 
	//do stuff
});

Sencha JS

Ext.onReady(function() {
	//do stuff
});

Be sure to let me know if I'm missing a framework -- I'd like this list to become as comprehensive as possible!

Recent Features

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

Incredible Demos

  • By
    CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...

  • By
    Use Custom Missing Image Graphics Using Dojo

    A few months back I posted an article about how you can use your own "missing image" graphics when an image fails to load using MooTools and jQuery. Here's how to do the same using Dojo. The HTML We'll delegate the image to display by class...

Discussion

  1. ExtJs still remains Extjs, Sencha is the company name…
    («One of the benefits of the name change is also that it separates a product name – Ext JS – from the company name, Sencha», http://www.sencha.com/blog/2010/06/14/ext-js-jqtouch-raphael-sencha/ )

    But everyone should still prefer Mootools :)

  2. Im not a programmer, but it seems to me that the mootools makes the most sense. You are adding an event listener to the window to see when the DOM is ready.

    Could just be that I like my event listeners.

  3. Jani Peltoniemi

    I like the Mootools way the most(Prototype doesn’t look bad either, just a little more complicated). Almost all other frameworks have a separate method for adding domready, which I find weird, since isn’t really different at all compared to regular events. It’s not a big deal but for beginners it might be easier to remember the event name of domready than the whole method for just that one task.

    I wonder what makes jQuery so popular? Is it the syntax? I’ve used Mootools for so long that everything else looks like clumsy when compared to it.

    • jQuery is the most popular because it’s “niche” is on what matters to most people, the DOM. Because jQuery has a shorter scope, it’s shorter to write and easy (many people feel it’s as easy as writing CSS).

      MooTools is programming, like a more improved flavor of JS. Since JS is such a different language from most, people don’t really want to deal with it anyway (so the easiest route is always selected).

      MooTools is comprehensive, and has a much steeper learning curve. Unless you were already programming, jQuery is MUCH more user-friendly.

  4. Allen

    Wow, is everything in YUI so verbose and convoluted? I’ve not really explored it–this example is solidifying that for the conceivable future.

    • Jorge Garcia

      No, YUI is not verbose and convoluted. The thing that there are two steps involved in the code snippet.

      The first line

      YUI().use('*',function(Y) {
      

      is creating your YUI sandbox and declaring which YUI modules should be loaded before actually executing the second line of code. This has pros and cons.

      One pro is that you can have more than one YUI sandbox in the same page and second your code is executed once every module has been loaded on demand.

      On the other examples the code assumes that you included everything necessary to run your code.

      Is an extra line but i think there are a lot of benefits.

  5. jQuery has an alternative/shorter ondomready:

    $(function(){
      //do stuff
    });
    
  6. jem

    I prefer the mootools approach myself. And I agree, the YUI code looks way too verbose, if the rest of the framework’s API translates to code like that then there’s reason in itself to avoid it.

    Mootools code has a tendency of looking cleaner in general to me (prototype is similar but it has very wordy method names), which I think is largely due to the fact it takes the approach of prototyping and extending native objects.

  7. Alex

    @Jani Peltoniemi
    I damn (totally^totally*+∞)>100% agree with you! Mootools syntax rocks so much that I don’t even dare to imagine myself using any other!

    @Allen
    YUI is the main reason I have delayed the creation of my first vBulletin4/Mootools style (template). Not only its syntax, pardon me, sucks, but it conflicts with other js frameworks. BTW, If I need to use a framework, I shall use only one. The one that is synonymous of FTW!!!

  8. To add on, jQuery has several other variations to fire a DOM ready f’n:

    $(function(){
    // $ code here
    });
    

    If $ has been released to the global namespace then this also works:

    jQuery(function($){
    // you can now use $ here
    });
    
  9. The thing I don’t like about the MooTools approach is that it’s on Window. Seems like document would be a more meaningful place.

    That being said, there’s also the native approach for browsers that support it (which is to say, pretty much everything but IE these days, and likely IE9):

    ​document.addEventListener('DOMContentLoaded', function () {
      // Etc
    }, false);​​​​​
    

    I love the libraries (particularly enamored with Dojo lately ;)) but it’s good to know how to do it raw too. :D

  10. Oh, also meant to mention that dojo does have dojo.ready as an alias for addOnLoad as of 1.4. :)

  11. @Brian Arnold: dojo.addOnLoad > dojo.ready

    “.ready” is too jQuery-ish for me.

  12. @Brian Arnold:

    Yeah

    document.addEvent('ready', function(){
    
    })
    

    or

    dom.addEvent('ready', function(){
    
    })
    

    would be the only think I would possibly change

  13. I can understand that, though one could make the argument that .ready is better, if for no other reason than saving four bytes. :)

    Also worth noting: addOnLoad (or ready, whichever) have more power inherently than the other libraries do — at least, that I’m aware of. For example, dojo.addOnLoad(obj, "someFunc") will run obj.someFunc when the DOM is ready, or dojo.addOnLoad(obj, function () {/*...*/}) will run the anonymous function scoped to obj.

    I know you could accomplish the latter by doing jQuery.ready(jQuery.proxy(function () {/*...*/}, obj), when using 1.4, and I’m sure other languages have similar (heck, native has bind in some newer browsers which would also do it). Still kind of a neat trick.

    Oh, also, addOnLoad, thanks to the require mechanics of Dojo, actually lets you do some sorts of lazy loading. You could chain things, like

    dojo.addOnLoad(function () {
      // Bind to some button stashed in some node variable
      dojo.connect(node, 'onclick', function (e) {
        // Need something new!
        dojo.require('some.other.thing');
        dojo.addOnLoad(function () {
          // This only runs once the required module has loaded
        }); // inner addOnLoad
      }); // connect
    }); // outer addOnLoad
    

    Which is also to say that technically, addOnLoad isn’t listening just for DOM to be ready, but for all required modules to be loaded, no matter how nested.

    A bit off-topic, I suppose, but it does show that things are a bit more powerful here. I suspect jQuery/RequireJS can do similar sorts of things, but I haven’t really dug into that yet.

  14. @Brian Arnold: The extremist in me says make it “dojo.r()” and save more bytes. :p

    Tru dat with addOnLoad working with required modules. MooTools has a bundled package that can create different Moo builds depending on what is needed on a given page.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!