12

Possible Duplicate:
javascript domready?

I want to check whether $(function(){ }); is "ready".

Return true if DOM is ready, false otherwise

Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Rephrase, please? I'm not quite understanding what you want. The DOM is ready right before the callback (in your example, the `function() {}`) runs. – cHao Dec 04 '11 at 07:22
  • People (including the jQuery API docs) call it the "document ready function". ;-) – Greg Pettit Dec 04 '11 at 07:29

4 Answers4

28

From jQuery code

if ( jQuery.isReady ) {  
    fn.call( document, jQuery );
} 

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • 6
    Just making a comment here that this is not a documented property and the authors of jQuery could change/remove this property at any time without notice. Use at your own risk and be careful when updating jQuery. – Ryan Wheale Feb 13 '13 at 01:47
15

You can use the explicit call

$(document).ready(function(){
  // do this after dom is ready
});

Or use the shortcut

$(function(){
  // do this after dom is ready
});

It's also useful to wrap your jQuery in an anonymous function when you're using other libraries; Also very common to use this when writing jQuery plugins.

(function($, window){
  // use $ here freely if you think any other library might have overridden it outside.
  $(function(){
    // do this after dom is ready
  });
})(jQuery, window);

Lastly, you can use jQuery.isReady (bool)

if (jQuery.isReady) {
  // do something
}
Om Shankar
  • 7,989
  • 4
  • 34
  • 54
maček
  • 76,434
  • 37
  • 167
  • 198
  • You can also do `jQuery(function($) { /* jQuery is aliased to $ inside this block even if another library is normally assigned to $ */ });` – redbmk Sep 25 '13 at 17:44
2

That function will only execute when the dom is ready. That's the point of wrapping your code in that function ;). Having said that, some things (like images, deferred scripts, etc.) might not be fully loaded or rendered yet, so be aware.

landons
  • 9,502
  • 3
  • 33
  • 46
1

You can use jQuery.isReady, but it's undocumented and should be avoided.

If you just need to run something after the DOM is ready, you can just call

$(document).ready(function() {
    ...
});

as normal – that will run the code immediately if the DOM is ready and wait until it is if not.

Yes Barry
  • 9,514
  • 5
  • 50
  • 69
Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238