jQuery最佳实践,在IIFE中使用$(document).ready吗? [英] JQuery best practice, using $(document).ready inside an IIFE?
问题描述
我正在看一段代码:
(function($) {
// other code here
$(document).ready(function() {
// other code here
});
})(jQuery);
我虽然IIFE可以执行$(document).ready的功能,但是此代码正确吗?或者我可以只删除$(document).ready并将代码直接放在IIFE内.
I though the IIFE does the functions of $(document).ready, is this code correct? or can I just remove the $(document).ready and place the code directly inside the IIFE.
推荐答案
否,IIFE不会在文档就绪状态下执行代码.
No, IIFE doesn't execute the code in document ready.
(function($) {
console.log('logs immediately');
})(jQuery);
此代码在文档未准备好的情况下立即运行,并立即记录立即日志".
This code runs immediately logs "logs immediately" without document is ready.
(function($) {
$(document).ready(function(){
console.log('logs after ready');
});
})(jQuery);
立即运行代码,等待文档准备就绪,并记录准备就绪后的日志".
Runs the code immediately and waits for document ready and logs "logs after ready".
这可以更好地理解:
(function($) {
console.log('logs immediately');
$(document).ready(function(){
console.log('logs after ready');
});
})(jQuery);
这将在窗口加载后立即将立即记录"记录到控制台,但仅在文档准备好后才记录准备好后记录".
This logs "logs immediately" to the console immediately after the window load but the "logs after ready" is logged only after the document is ready.
$(document).ready(function(){})
的替代方案是:
$(function(){
//code in here
});
更新
从jQuery 3.0版开始,更改了ready处理程序.
Update
From jQuery version 3.0, the ready handler is changed.
jQuery(function($) {
});
$(function() {
console.log("inside handler");
});
console.log("outside handler");
>外部处理程序
> outside handler
>内部处理程序
这篇关于jQuery最佳实践,在IIFE中使用$(document).ready吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!