Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 781
Armatus Avatar asked Nov 03 '22 18:11

Armatus


1 Answers

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');
like image 89
Maxim Krizhanovsky Avatar answered Nov 15 '22 05:11

Maxim Krizhanovsky