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

红色:

我正在研究jQuery最佳做法,并发现Greg Franko的这篇文章

通常,我会:

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

但本文建议使用:

// 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

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

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

我知道这两种方法都行得通,但是第二种方法如何变得更好

格雷格·弗兰科(Greg Franko):

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

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

如果您不想滚动到源文件的底部来查看要传递给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!

      }
  ));

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

jQuery Ready事件

许多开发人员将所有代码包装在jQuery ready事件中,如下所示:

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

或更短的版本是这样的:

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

如果您正在执行上述两种模式,则应考虑将不依赖DOM的应用程序部分(例如方法)移到ready事件处理程序之外。像这样:

   // 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!

      }
  ));

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

改编自我的jQuery Best Practices博客文章:http : //gregfranko.com/blog/jquery-best-practices/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章