gpt4 book ai didi

javascript - 我应该将 jQuery 文档包装在自执行函数中吗?

转载 作者:行者123 更新时间:2023-12-01 02:15:06 27 4
gpt4 key购买 nike

我想做这样的事情:

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

您认为这种做法是好还是坏?它对 jQuery(document).ready() 何时触发有任何影响吗?

最佳答案

我想说的唯一原因是,如果您在 DOM 准备就绪之前需要运行一些 javascript,并且您不想污染全局命名空间。

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

关于javascript - 我应该将 jQuery 文档包装在自执行函数中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6538789/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com