Javascript 我应该如何初始化 jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2215904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:16:25  来源:igfitidea点击:

How should I initialize jQuery?

javascriptjquery

提问by Reigel

I have seen this (I'm also using it):

我见过这个(我也在使用它):

$(document).ready(function(){
   // do jQuery
})

and also this (I have tried lately):

还有这个(我最近试过):

(function(){
   // do jQuery
})(jQuery)

both work fine.

两者都工作正常。

What is the difference of the two (except on how it looks)?

两者有什么区别(除了外观)?

Which one is more proper to use?

哪个更适合使用?

采纳答案by Jacob Relkin

The first example runs the function when the DOM tree is built. The second example runs the function right away.

第一个示例在构建 DOM 树时运行该函数。第二个示例立即运行该函数。

If you look closely, in the second example, there are two parentheses after the function declaration ( in this particular case, you pass in the global jQueryobject as an argument to avoid conflict ), thereby immediately invoking the function

如果仔细观察,在第二个示例中,函数声明后有两个括号(在这种特殊情况下,您将全局jQuery对象作为参数传入以避免冲突),从而立即调用函数

The right function to use depends on when you want the function to run. If you want to run a function on DOMReady( the readyevent ), you can use $( document ).readylike you mentioned or the shorthand $( function() {...} ).

要使用的正确函数取决于您希望函数何时运行。如果你想在DOMReadyready事件)上运行一个函数,你可以使用$( document ).ready你提到的或简写$( function() {...} )

Otherwise, if you want to run a function immediately and have anonymous function scope, use the second example.

否则,如果您想立即运行函数并具有匿名函数作用域,请使用第二个示例。

回答by Doug Neiner

The second example you show is a self executing anonymous function. Every separate JS file you use would probably benefit from using it. It provides a private scope where everything you declare with the varkeyword remains inside that scope only:

您展示的第二个示例是一个自执行匿名函数。您使用的每个单独的 JS 文件都可能会从使用中受益。它提供了一个私有范围,您使用var关键字声明的所有内容仅保留在该范围内:

(function($){
   var special = "nice!";
})(jQuery);

alert(special); // would be undefined

The first example is shorthand for $(document).readywhich fires when the DOM can be manipulated.

第一个示例是$(document).ready可以操作 DOM 时触发的简写。

A couple cool things about it. First, you can use it inside the self executing function:

关于它的一些很酷的事情。首先,您可以在自执行函数中使用它:

(function($){
   $(function(){
      // Run on DOM ready
   });

   // Run right away
})(jQuery);

Secondly, if all you need is a few lines in document ready, you can combine both the private scope and the DOM ready function like this:

其次,如果您只需要准备好文档中的几行,您可以像这样组合私有范围和 DOM 就绪函数:

jQuery(function($){
   // $ = jQuery regardless of what it means
   // outside this DOM ready function
});

回答by Ashraf Abusada

In addition to all the previous answers, jQuery have three initialization methods that can be used:

除了前面所有的答案,jQuery 还提供了三种可以使用的初始化方法:

The traditional method compatible with most browsers, see code:

传统方式兼容大部分浏览器,见代码:

$(document).ready(function () {

        });

The short-hand method, see code:

简写方法,见代码:

$(function () {

        });

The implicit method, see code:

隐式方法,见代码:

$().ready(function () {

        });

They all work for modern browsers and safe to use.

它们都适用于现代浏览器并且可以安全使用。

回答by morgancodes

I always use the first. The second appears to be a way to protect against jquery being overriden. One reason you might do this is if you don't know what other scripts will be loaded on the page. If all of your stuff depends on, say, jquery 1.3, and you're in an environment where you don't control the entire page, your code could break if someone loads in jquery 1.4. Sounds ugly, but this sort of thing does happen. So you can cover your butt by creating a closure immediately after you load jquery, and holding your version of jquery inside that closure. I think that's what's going on in the second example.

我总是用第一个。第二种似乎是一种防止 jquery 被覆盖的方法。这样做的一个原因是,如果您不知道页面上将加载哪些其他脚本。如果您的所有内容都依赖于 jquery 1.3,并且您处于无法控制整个页面的环境中,那么如果有人加载 jquery 1.4,您的代码可能会中断。听起来很丑,但这种事情确实发生了。因此,您可以在加载 jquery 后立即创建一个闭包,并将您的 jquery 版本保存在该闭包中,从而覆盖您的屁股。我认为这就是第二个例子中发生的事情。

Neither one actually initializes jquery. Jquery takes care of any initilazation it needs on its own. You'd still, quite likely wind up using the first example even if you were using the second, you'd just be putting the $(document).ready insidethe function in your second example.

两者都没有真正初始化 jquery。Jquery 自行处理它需要的任何初始化。即使您正在使用第二个示例,您仍然很可能会使用第一个示例,您只需将 $(document).ready放在第二个示例的函数中。

回答by Munna Khan

Though it's an old conversation, I want to share my way to init jQuery

虽然这是一个古老的对话,但我想分享我初始化 jQuery 的方法

;(function($, window, document) {

    // Your Code Goes Here

}(window.jQuery, window, document));

By this, you can sure about that nothing can go wrong.

通过这一点,您可以确定不会出错。