javascript $('document').ready 情况下的 jQuery 最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18307078/
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-10-27 11:24:22  来源:igfitidea点击:

jQuery best practices in case of $('document').ready

javascriptjquerydesign-patternscode-standards

提问by Red

I was researching on jQuery best practices and found thisarticle by Greg Franko

我正在研究 jQuery 最佳实践,并找到了 Greg Franko 的这篇文章

Normally, I do:

通常,我这样做:

$("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here
});

But the article recommends to use:

但是文章推荐使用:

// IIFE - Immediately Invoked Function Expression
(function($, window, document) {

    // The $ is now locally scoped 

    // Listen for the jQuery ready event on the document
    $(function() {

        // The DOM is ready!

    });

    // The rest of the code goes here!

}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter

I can see the comments there, but I couldn't figure out what it exactly saying.

我可以看到那里的评论,但我无法弄清楚它到底在说什么。

So, which is the better approach and why?

那么,哪种方法更好,为什么?

I know that both methods will work, but how does the second one become the better?

我知道这两种方法都有效,但第二种方法如何变得更好

回答by Greg Franko

Immediately Invoked Function Expressions (IIFEs)

立即调用函数表达式 (IIFE)

IIFEs are an ideal solution for locally scoping global variables/properties and protecting your JavaScript codebase from outside interference (e.g. third-party libraries). If you are writing jQuery code that will be run in many different environments (e.g. jQuery plugins), then it is important to use an IIFE to locally scope jQuery because you can't assume everyone is using the $ to alias jQuery. Here is how you would do it:

IIFE 是本地范围全局变量/属性和保护您的 JavaScript 代码库免受外部干扰(例如第三方库)的理想解决方案。如果您正在编写将在许多不同环境中运行的 jQuery 代码(例如 jQuery 插件),那么使用 IIFE 来局部限定 jQuery 是很重要的,因为您不能假设每个人都使用 $ 来为 jQuery 设置别名。以下是您的操作方法:

   // IIFE - Immediately Invoked Function Expression
  (function($, window, document) {
      // The $ is now locally scoped

      // The rest of your code goes here!

  }(window.jQuery, window, document));
  // The global jQuery object is passed as a parameter

If you don't like having to scroll to the bottom of your source file to see what global variables/properties you are passing to your IIFE, you can do this:

如果您不想滚动到源文件的底部以查看传递给 IIFE 的全局变量/属性,您可以这样做:

   // IIFE - Immediately Invoked Function Expression
  (function(yourcode) {

      // The global jQuery object is passed as a parameter
      yourcode(window.jQuery, window, document);

      }(function($, window, document) {

          // The rest of your code goes here!

      }
  ));

To read more about IIFEs, you can read my blog post titled, I Love My IIFE.

要了解有关 IIFE 的更多信息,您可以阅读我的博客文章,我爱我的 IIFE

jQuery Ready Event

jQuery 就绪事件

Many developers wrap all of their code inside of the jQuery ready event like this:

许多开发人员将他们的所有代码封装在 jQuery 就绪事件中,如下所示:

   $("document").ready(function() {
      // The DOM is ready!
      // The rest of your code goes here!
  });

Or a shorter version like this:

或者像这样的较短版本:

   $(function() {
      // The DOM is ready!
      // The rest of your code goes here!
  });

If you are doing either of the above patterns, then you should consider moving the pieces of your application (e.g. methods), that don't depend on the DOM, outside of the ready event handler. Like this:

如果您正在执行上述任一模式,那么您应该考虑将不依赖于 DOM 的应用程序部分(例如方法)移到就绪事件处理程序之外。像这样:

   // IIFE - Immediately Invoked Function Expression
  (function(yourcode) {

      // The global jQuery object is passed as a parameter
      yourcode(window.jQuery, window, document);

      }(function($, window, document) {

          // The $ is now locally scoped 
          $(function() {

              // The DOM is ready!

          });

          // The rest of your code goes here!

      }
  ));

This pattern makes it easier to separate your logic(from a code design perspective) since not everything has to be wrapped inside of a single event handler callback function. It will also improve your application's page load performance, since not everything needs to initialized right away. A great example of this is lazy binding DOM event handlersthat do not need to be bound when the DOM is ready.

这种模式可以更轻松地分离您的逻辑(从代码设计的角度来看),因为并非所有内容都必须包含在单个事件处理程序回调函数中。它还将提高应用程序的页面加载性能,因为并非所有内容都需要立即初始化。一个很好的例子是延迟绑定 DOM 事件处理程序,当 DOM 准备好时不需要绑定它。

Adapted from my jQuery Best Practices blog post: http://gregfranko.com/blog/jquery-best-practices/

改编自我的 jQuery 最佳实践博客文章:http: //gregfranko.com/blog/jquery-best-practices/

回答by Blender

The only difference between your code and the "suggested" approach is compatibility and possibly better compression. There are no speed differences.

您的代码和“建议”方法之间的唯一区别是兼容性和可能更好的压缩。没有速度差异。

Passing window.jQueryas the first argument to your IIFE (immediately-invoked function expression) and naming it $within the IIFE will just allow you to use jQuery without interfering with other libraries that assign themselves to the global $. If you don't use any other libraries that assign themselves to the global $, the first argument to your IIFE isn't going to serve any purpose.

window.jQuery作为第一个参数传递给您的 IIFE(立即调用的函数表达式)并$在 IIFE 中命名它只会允许您使用 jQuery 而不会干扰将自己分配给全局$. 如果您不使用将自己分配给 global 的任何其他库$,则您的 IIFE 的第一个参数将不会用于任何目的。

Passing windowand documentto your IIFE will allow JS minifiers to transform your code into something like this (without the whitespace), which gives you slightly better compression:

window和传递document给你的 IIFE 将允许 JS 压缩器将你的代码转换成这样的东西(没有空格),这会给你更好的压缩:

(function(a, b, c) {
    a(c).ready(function() {
        // ...
    });
})(window.jQuery, window, document);

Unless you use windowand documentextensively, I would just do:

除非您广泛使用windowdocument,否则我会这样做:

;(function($) {
    $(function() {
        ...
    });
})(jQuery);

回答by dwerner

  1. $(function(){})is equivalent to $('document').ready(function(){});. It's up to you which you use, but the latter is the older of the two, and more verbose to boot.

  2. The second approach you have listed is an explicit attempt to prevent global variables, and injects the known globals $, window, and document. This is recommended to increase awareness of how easily globals are introduced, and be as 'clean-room' as possible about the code we are injecting to the page. Also, note that the second approach is not equivalent to the first if you follow the comments shown. Because $ is inserted as an argument, this code is compatible with other libraries that may desire to own the $ symbol.

  1. $(function(){})相当于$('document').ready(function(){});。使用哪种取决于您,但后者是两者中较旧的,并且启动起来更冗长。

  2. 您列出的第二种方法是一个明确的企图阻止全局变量,并注入已知的全局$windowdocument。建议这样做以提高对引入全局变量的容易程度的认识,并尽可能对我们注入页面的代码保持“洁净室”。另外,请注意,如果您遵循显示的注释,则第二种方法与第一种方法不同。因为 $ 作为参数插入,此代码与可能希望拥有 $ 符号的其他库兼容。

In particular, // The rest of the code goes hereis in a place that may be executed before the document is ready, or when that event is fired. Put it inside the function passed to $.

特别是,// The rest of the code goes here在文档准备好之前或在触发该事件时可能会执行的地方。把它放在传递给 $ 的函数中。

回答by Balaji Kandasamy

Your link has the anwser:

你的链接有答案:

The below is fine,

下面就好了

If you know the environments where your code will run.

如果您知道代码将运行的环境。

If you do not care about page load performance.

如果您不关心页面加载性能。

If you don't care about best practices.

如果您不关心最佳实践。

 $("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });

But they recommend, its better to use like below for, If you don't know the environment where your code will run and

但他们建议,最好像下面这样使用,如果你不知道你的代码将运行的环境和

Better page load performance

更好的页面加载性能

// IIFE - Immediately Invoked Function Expression
  (function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }(window.jQuery, window, document));
  // The global jQuery object is passed as a parameter

回答by palerdot

If you use $ as an alias for jQuery then

如果你使用 $ 作为 jQuery 的别名,那么

   $(document).ready(function(){})

is same as

  (function($, window, document) {

  // The $ is now locally scoped 

 // Listen for the jQuery ready event on the document
  $(function() {

    // The DOM is ready!

  });

  // The rest of the code goes here!

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

As pointed out in an earlier answer, the second method insulates you from using $ alias freely for jQuery as it passes the jQuery object to the Immediately invoked function expression, which basically keeps the variables and code within it private, and does not pollute the global namespace.

正如在前面的回答中指出的那样,第二种方法使您免于为 jQuery 自由使用 $ 别名,因为它将 jQuery 对象传递给立即调用的函数表达式,这基本上保持其中的变量和代码私有,并且不会污染全局命名空间。

In short, if you resort to the first method and use other libraries using $, you will end with conflict.

简而言之,如果你诉诸第一种方法并使用$使用其他库,则会以冲突结束。

回答by Maciej Gurban

In the rare situation when you'll have to work on an older jQuery version (if I recall correctly - pre 1.8.X), whenever you'd specify two document.ready blocks, only the first one would be fired in IE9.

在极少数情况下,您必须使用较旧的 jQuery 版本(如果我没记错的话 - 1.8.X 之前的版本),每当您指定两个 document.ready 块时,在 IE9 中只会触发第一个块。

Now this is a rare bug I experienced once, or twice and which I fail to be able to reproduce, but I thought it would be worth noting.

现在这是我遇到过一次或两次并且无法重现的罕见错误,但我认为这值得一提。

回答by rderoldan1

Based in Jquery documentation:

基于 Jquery 文档:

All three of the following syntaxes are equivalent:

$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)

http://api.jquery.com/ready/

http://api.jquery.com/ready/

回答by Rohan Kumar

It's called a self ivokingor immediately invokedfunction. It means that the function is run as soon as it is created using the parameters in the final set of brackets.

它被称为 aself ivokingimmediately invoked函数。这意味着该函数在使用最后一组括号中的参数创建后立即运行。

Read Javascript Self Invoking Functionsand Immediately-Invoked Function Expression (IIFE)will clear where to use and how to use these functions

阅读Javascript 自调用函数立即调用函数表达式 (IIFE)将清楚在哪里使用以及如何使用这些函数

回答by Nimesh khatri

You can use document ready event using jquery, event occure when document is fully loaded.

您可以使用 jquery 使用文档就绪事件,当文档完全加载时发生事件。

 $(function () {
    setTimeout(function () {
        // your code
    }, 0);
})