I was told to use document.ready when I first started to use Javascript/jQuery but I never really learned why.

Might someone provide some basic guidelines on when it makes sense to wrap javascript/jquery code inside jQuery's document.ready?

Some topics I'm interested in:

  1. jQuery的.on()方法:我经常在AJAX中使用.on()方法(通常在动态创建的DOM元素上)..on()点击处理程序always应该是inside document.ready吗?
  2. Performance: Is it more performant to keep various javascript/jQuery objects inside or outside document.ready (also, is the performance difference significant?)?
  3. 对象范围:AJAX加载的页面无法访问上一页文档中包含的对象.准备好了吗?他们只能访问文档中包含的对象.准备好了吗(即真正的"全局"对象)?

Update:为了遵循最佳实践,我的所有javascript(jQuery库和我的应用程序代码)都位于HTML页面的bottom处,我在jQuery上使用defer属性,该属性包含AJAX加载页面上的脚本,以便我可以访问这些页面上的jQuery库.

推荐答案

简单地说,

$(document).ready is an event which fires up when document is ready.

假设您已将jQuery代码放在head部分,并试图访问dom元素(锚、img等),您将无法访问它,因为html是从上到下解释的,并且jQuery代码运行时您的html元素不存在.

To overcome this problem, we place every jQuery/javascript code (which uses DOM) inside $(document).ready function which gets called when all the dom elements can be accessed.

这就是为什么,当您将jQuery代码放在底部时(在所有dom元素之后,刚好在</body>之前),there is no need for 101

仅当您在document上使用on方法时,才不需要将on方法放入$(document).ready中,原因与我上面解释的原因相同.

    //No need to be put inside $(document).ready
    $(document).on('click','a',function () {
    })

    // Need to be put inside $(document).ready if placed inside <head></head>
    $('.container').on('click','a',function () {
    });

EDIT

从 comments 来看,

  1. $(document).ready不等待图像或脚本.这就是$(document).ready$(document).load之间的巨大差异

  2. Only code that accesses the DOM should be in ready handler. If it's a plugin, it shouldn't be in the ready event.

Jquery相关问答推荐

在页面上放置文件时如何设置文件输入值?

如何使用 jQuery 的 getJSON() 方法传递请求标头?

如何使用jquery取消绑定所有事件

非 AJAX jQuery POST 请求

jQuery增量读取AJAX流?

jQuery计算所有文本字段中的值的总和

使用 时如何从 select2 中获取选定文本

使用 MVC、C# 和 jQuery 导出为 CSV

将打开/关闭图标添加到 Twitter Bootstrap 可折叠项(手风琴)

触发下拉更改事件

按文本 Select 链接(完全匹配)

什么时候应该使用 jQuery deferred 的then方法,什么时候应该使用pipe方法?

变量首字母大写

在事件中使用 jQuery 获取被点击的元素?

如何获取第一个元素而不是在 jQuery 中使用 [0]?

在jQuery中获取列表元素内容的数组

如何禁用由子元素触发的 mouseout 事件?

jQuery,简单的轮询示例

jQuery中的wait()或sleep()函数?

清除表jquery