javascript 什么时候需要使用 $(document).ready()?

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

when do you need to use $(document).ready()?

javascriptjquery

提问by hannasm

I'm curious what situations exactly require the use of jquery's $(document).ready() or prototype's dom:loaded or any other variant of a handler for this event.

我很好奇什么情况下需要使用 jquery 的 $(document).ready() 或原型的 dom:loaded 或此事件的处理程序的任何其他变体。

In all the browsers i've tested, it's entirely acceptable to begin interacting with html elements and the DOM immediately after the closing tag. (e.g.

在我测试过的所有浏览器中,在结束标记之后立即开始与 html 元素和 DOM 交互是完全可以接受的。(例如

<div id="myID">
 My Div
</div>
<script type="text/javascript">
$('#myID').initializeElement();
</script>

So at this point i'm wondering whether $(document).ready()is merely there to reduce the thinking involved in writing javascript code that runs during page load. In the case of using $(document).ready()there is regularly rendering issues such as popping and 'artifacts' between the browser first starting to draw the page and the javascript actually executing when the page is 'ready'.

所以在这一点上,我想知道是否$(document).ready()仅仅是为了减少编写在页面加载期间运行的 javascript 代码所涉及的思考。在使用的情况下,$(document).ready()在浏览器首先开始绘制页面和页面“准备好”时实际执行的 javascript 之间经常会出现诸如弹出和“工件”之类的渲染问题。

Are there any scenarios where $(document).ready()is required?

是否有任何$(document).ready()需要的场景?

Are there any reasons I shouldn't be writing initialization scripts as demonstrated?

是否有任何原因我不应该像演示的那样编写初始化脚本?

采纳答案by hannasm

In the case of external scripts $(document).ready() could be the only option. As for inline script it is a little different.

在外部脚本的情况下, $(document).ready() 可能是唯一的选择。至于内联脚本,它有点不同。

According to HTML 4.01 standard it seems a little ambiguous whether or not the initialization technique shown above is legal:

根据 HTML 4.01 标准,上面显示的初始化技术是否合法似乎有点模棱两可:

http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.4

Scripts that are executed when a document is loaded may be able to modify the document's contents dynamically. The ability to do so depends on the scripting language itself (e.g., the "document.write" statement in the HTML object model supported by some vendors).

HTML documents are constrained to conform to the HTML DTD both before and after processing any SCRIPT elements.

http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.4

加载文档时执行的脚本可能能够动态修改文档的内容。这样做的能力取决于脚本语言本身(例如,某些供应商支持的 HTML 对象模型中的“document.write”语句)。

HTML 文档在处理任何 SCRIPT 元素之前和之后都被约束为符合 HTML DTD。

In the HTML 5 draft it seems very clear that this practice is fully supported:

在 HTML 5 草案中,似乎很清楚这种做法是完全支持的:

http://www.w3.org/TR/html5/scripting-1.html#scripting-1

The following sample shows how a script element can be used to define a function that is then used by other parts of the document. It also shows how a script element can be used to invoke script while the document is being parsed, in this case to initialize the form's output.

http://www.w3.org/TR/html5/scripting-1.html#scripting-1

下面的示例展示了如何使用脚本元素来定义一个函数,然后该函数被文档的其他部分使用。它还展示了如何在解析文档时使用脚本元素调用脚本,在本例中用于初始化表单的输出。

<script>
 function calculate(form) {
   var price = 52000;
   if (form.elements.brakes.checked)
     price += 1000;
   if (form.elements.radio.checked)
     price += 2500;
   if (form.elements.turbo.checked)
     price += 5000;
   if (form.elements.sticker.checked)
     price += 250;
   form.elements.result.value = price;
 }
</script>
<form name="pricecalc" onsubmit="return false">
 <fieldset>
  <legend>Work out the price of your car</legend>
  <p>Base cost: £52000.</p>
  <p>Select additional options:</p>
  <ul onchange="calculate(form)">
   <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
   <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
   <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
   <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
  </ul>
  <p>Total: £<output name=result></output></p>
 </fieldset>
 <script>
  calculate(document.forms.pricecalc);
 </script>
</form>

回答by Raynos

The main reason is external filesthat are included in the head. When you include a file in your <head>it gets run immediately. This means if the JavaScript interacts with the DOM it needs to be wrapped in Dom Ready.

主要原因是包含在头部的外部文件。当你在你的文件中包含一个文件时,<head>它会立即运行。这意味着如果 JavaScript 与 DOM 交互,它需要被包裹在 Dom Ready 中。

It's also needed for unobtrusive JavaScript and separations of concerns. Ideally your JavaScript and HTML are in separate files. If you follow this you will not have any in-line script tags in your HTML at all.

不显眼的 JavaScript 和关注点分离也需要它。理想情况下,您的 JavaScript 和 HTML 位于不同的文件中。如果您按照此操作,您的 HTML 中将不会有任何内嵌脚本标签。

The second is to defend yourself against obscure browser bugs when you make mistakes. There are cases where it's not save to go and manipulate DOM elements immediately afterwards. (I'm looking at you IE6!)

第二个是在你犯错时保护自己免受晦涩的浏览器错误。在某些情况下,之后立即去操作 DOM 元素并不能保存。(我在看你IE6!)

The third reason is to keep your code clean.

第三个原因是保持你的代码干净。

Mixing script tags into your HTML makes spaghetti code.

将脚本标签混合到您的 HTML 中会生成意大利面条式代码。

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

We have code about ten times worse then that. It's a right pain to read / maintain

我们的代码比那糟糕十倍。阅读/维护是一种正确的痛苦

回答by user622378

Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

一旦 DOM 加载完毕且在页面内容加载之前,它里面的所有内容都会加载。

The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML

$(document).ready() 函数比其他让事件起作用的方法有很多优势。首先,您不必在 HTML 中放置任何“行为”标记

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.

使用 $(document).ready(),您可以在窗口加载之前加载或触发事件或任何您希望它们执行的操作。