Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcuts for jQuery's ready() method

I have seen some shortcuts for the ready() method and would like to know which actually happens first, because my test results confuse me..

$(document).ready(function(){     alert("document ready"); });  $(window).load(function(){     alert("window ready"); });  (function($){     alert("self invoke"); })(jQuery); 

Here self invoke happens first, then document, then window. Is the self invoke technique considered a ready() method?

like image 268
Wilkins Avatar asked Oct 11 '10 15:10

Wilkins


People also ask

How do I use document ready function?

$( document ). ready() A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).

What is the purpose of Ready () function?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Can we use ready () function more than once?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served. In below code you will be cleared.


1 Answers

The third option is not a shortcut for .ready() (or jQuery related really), the self invoke runs immediately (as soon as it appears in the code), this is probably the shortcut you're thinking of though:

$(function(){   alert("I'm a ready shortcut"); }); 

Passing a function into $(func) is a shortcut for $(document).ready(func);. The no-conflict version would look like this:

jQuery(function($) {   //$ is jQuery }); 
like image 107
Nick Craver Avatar answered Oct 04 '22 11:10

Nick Craver