I am including all of my JS as external files that are loaded at the very bottom of the page. Within these files, I have several methods defined like so, which I call from the ready event:

var SomeNamepsace = {};

SomeNamepsace.firstMethod = function () {
    // do something
};

SomeNamepsace.secondMethod = function () {
    // do something else
};

$(document).ready(function () {
    SomeNamepsace.firstMethod();
    SomeNamepsace.secondMethod();
});

However, when I remove the ready function and call the methods straight-up, everything works just the same, but executes significantly faster—almost a whole second faster on a pretty basic file! Since the document should be loaded at this point (as all the markup comes before the script tags), is there any good reason to still be using the ready event?

推荐答案

问得好.

关于"将脚本放在页面底部"的建议以及它试图解决的问题,存在一些困惑.对于这个问题,我不打算谈论将脚本放在页面底部是否会影响性能/加载时间.我只想谈谈你是否需要$(document).ready if you also put scripts at the bottom of the page.

我假设您正在脚本中立即调用的那些函数中引用DOM(简单到documentdocument.getElementById).我还假设您只询问这些[DOM引用]文件.现在,库脚本或DOM引用代码所需的脚本(如jQuery)需要放在页面的前面.

To answer your question: if you include your DOM-referencing scripts at the bottom of the page, No, you do not need $(document).ready.

Explanation: without the aid of "onload"-related implementations like $(document).ready the rule of thumb is: any code that interacts with DOM elements within the page should to be placed/included further down the page than the elements it references. The easiest thing to do is to place that code before the closing </body>. See here and here. It also works around IE's dreaded "Operation aborted" error.

话虽如此,这并不意味着$(document).ready的使用是无效的.在加载对象之前引用它是开始使用DOM JavaScript时最常见的错误之一(见过太多次,数不清).它是jQuery对该问题的解决方案,您不必考虑该脚本相对于其引用的DOM元素将包含在何处.这对开发者来说是一个巨大的胜利.他们只需要少考虑一件事.

此外,将所有DOM引用脚本移到页面底部通常很困难或不切实际(例如,任何发出document.write个调用的脚本都必须保持不变).其他时候,您使用的框架呈现一些模板或创建动态javascript片段,其中引用了需要包含在js中的函数.

最后,过go 将所有DOM引用代码塞进window.onload是"最佳实践",但well document reasons年来,$(document).ready个实现让它黯然失色.

All this adds up to $(document).ready as a far superior, practical and general solution to the problem of referencing DOM elements too early.

Jquery相关问答推荐

如何在for循环期间上传文件

在函数 jQuery 中更改语言

通过 .push() 方法向对象添加项目

jquery克隆div并将其附加在特定div之后

在 Bootstrap 3 中向工具提示添加换行符

在文本框中的最后一个字符之后设置焦点

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

使用 jQuery 的并行异步 Ajax 请求

不使用插件的 jQuery 缓动函数

延迟后运行功能

Angular.js 在多个元素中重复

如何使用 jQuery 进行带命名空间的 XML 解析

如何在我的 WordPress 插件中包含 CSS 和 jQuery?

复选框值始终为打开

一组元素中具有最大高度的元素

Rails 无法正确解码来自 jQuery 的 JSON(数组变成带有整数键的散列)

Google 的 CDN 上的最新 jQuery 版本

如何在没有鼠标事件的情况下在 jQuery 中获取鼠标位置?

.animate() 的回调被调用两次 jquery

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