Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I wrap jQuery document ready in a self executing function?

I had a thought to do something like this:

(function(window, undefined){
    $ = window.jQuery;
    $(function(){
        // Do some stuff
    });     
})(this);

Would you consider this good practice or bad? Does it have any implications for when jQuery(document).ready() would fire?

like image 663
Cros Avatar asked Jan 21 '26 19:01

Cros


1 Answers

Only reason I'd say would be if you have some javascript to run before the DOM is ready, and you don't want to pollute the global namespace.

(function(window, undefined){
    var $ = window.jQuery;

    // create some variables and/or functions that shouldn't be global
    //    ...and do some work before the "ready()" fires
    var a = 'some value';
    function b() {
        // do some important stuff
    }
    var c = b();

    // Maybe set up a `.live()` handler, which doesn't rely on DOM ready.
    $('.someSelector').live( function() {
        // Some handler code.
        // This works before DOM is ready.
    });

    $(function(){
        // Your DOM ready code
    });     
})(this);
like image 89
user113716 Avatar answered Jan 23 '26 08:01

user113716