Armatus
Armatus

Reputation: 2191

How does jQuery.ready() treat a call to itself?

As an example:

$( function(){
    //do stuff
    $( function(){
        //do other stuff
    });
});

Of course written out in code this seems to make no sense. But a plugin which works with HTML elements may use .ready() while itself being executed on an element in the main script's .ready(). How does jQuery handle this exactly? It clearly works, but does it do anything special?

Upvotes: 5

Views: 84

Answers (1)

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

This means that when the first function is executed, the inner one will be executed immediately

Additionally, jQuery allows you to bind multiple functions to a single event and it will call them all (assuming that no one produces an error)

You can test the behaviour by executing on already loaded page:

jQuery(document).ready(function(){
        for(i=0;i<1000000;i++);
        console.log('2');
    });
console.log('1');

Upvotes: 2

Related Questions