开发者

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?


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);


It's not needed. Using a self executable function creates a scope which makes so the variable you create into that scope do not become global.

var a = 'Hi';
alert(window.a); // "Hi"

(function () {
    var a = 'Hi';
})();
alert(window.a); // "undefined"

In the case of jQuery, it's not needed. The ready function creates a scope already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜