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
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    dat.gui:  Exceptional JavaScript Interface Controller

    We all love trusted JavaScript frameworks like MooTools, jQuery, and Dojo, but there's a big push toward using focused micro-frameworks for smaller purposes. Of course, there are positives and negatives to using them.  Positives include smaller JS footprint (especially good for mobile) and less cruft, negatives...

  • By
    Detect Vendor Prefix with JavaScript

    Regardless of our position on vendor prefixes, we have to live with them and occasionally use them to make things work.  These prefixes can be used in two formats:  the CSS format (-moz-, as in -moz-element) and the JS format (navigator.mozApps).  The awesome X-Tag project has...

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!