Sunday, April 8, 2012

Why does $($) crash my page?



Disclaimer: Do not try this at home








Why, if I am using jQuery, does $($) freeze the page?








Inspired by this Area51 question



Source: Tips4all

3 comments:

  1. $($) is a shortcut for $(document).ready($). So, it will run the function (when the DOM is ready or directly when this is already the case).

    The function passed to .ready is passed the jQuery function for convenience (especially useful when you're in noConflict mode). So, $($) will call $ with $ as argument - and everything will happen again, which is endless recursion.



    Another explanation:


    You call $($).
    jQuery adds the function argument ($) to an internal ready list.
    Some time later, jQuery sees that the DOM is ready and thinks: "Let's call all functions in the ready list".
    The only function in the ready list is $, so it calls $.
    jQuery sees it should pass the $ function as the argument to those functions.
    It calls $ with $ as argument.
    The $ function sees a function as its argument, but because the DOM is ready, it calls the function directly (there is nothing to wait for).
    The function is called with $ as the argument.
    Everything happens again since step 7 applies.

    ReplyDelete
  2. Now this is what I call "jQueryception."

    You're calling whole jQuery library within jQuery.

    More information;

    When you call "$" (defined as jQuery core function by jQuery library) it initializes the jQuery and tries to call the defined function if it has one. When you actually call "$($);" you'll be calling jQuery inside jQuery and it'll be calling jQuery again and again.

    From jQuery 1.7.1 source code;

    // HANDLE: $(function)
    // Shortcut for document ready
    } else if ( jQuery.isFunction( selector ) ) {
    return rootjQuery.ready( selector );
    }


    And

    rootjQuery = jQuery(document);


    As you can see, when you call $($); it tries to call jQuery with the name of your function and if you call it with jQuery again same thing will happen endlessly as I've explained before.

    ReplyDelete
  3. $ is an alias to the jQuery factory function.

    The jQuery factory function, when passed a function as first param, runs that function at document.ready and passes jQuery as the first parameter to it.

    Thus you end up with a infinite recursion starting when document.ready is reached.

    ReplyDelete