是否真的有必要等待DOM准备好操纵DOM? [英] Is it really necessary to wait for DOM ready to manipulate the DOM?

查看:102
本文介绍了是否真的有必要等待DOM准备好操纵DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您的代码仅操作已经完全解析的DOM元素,那么真的有必要等待ready(或window.onload)事件吗?

Is it really necessary to wait for the "ready" (or "window.onload") events if your code only manipulates DOM elements that have already been parsed entirely?

ready()功能的jQuery文档演示了如何等待执行操作直到DOM完全准备就绪,但该示例是针对所讨论的DOM元素之前列出的代码(脚本标记)。但是,似乎在HTML文档中必需的DOM元素之后出现的代码可以访问它们,因为可能是在浏览器解析文档时构建了DOM。

The jQuery documentation for the "ready()" function demonstrates how you could wait to perform actions until the DOM is entirely ready but the example is for code (script tags) that are listed before the DOM elements in question. But it seems that code which appears after the necessary DOM elements in an HTML document has access to them since, presumably, the DOM is built as the browser parses the document.

例如,可以安全地假设以下代码在所有情况下都是可靠的,还是使用ready / onload处理程序仍然是必要的(或有所帮助)?

For example, is it safe to assume that the following code is reliable in all situations or is it still necessary (or beneficial somehow) to use a ready/onload handler?

<body>
  <div id="foo"/>
  <script type="text/javascript">
    var foo = document.getElementById('foo');
    foo.innerHTML = 'The element #foo is loaded!';
  </script>
</body>

非常相似,但是我想碰到它,看看是否有更多的信息。

This SO question is very similar but I wanted to bump it to see if there is any more information.

推荐答案

如果您的JavaScript代码位于DOM元素下方,并且仅仅修改它们,则不需要等待DOM就绪事件。

If your JavaScript code is below the DOM elements and only modifies them exclusively, you don't need to wait for the DOM ready event.

但是,请牢记编辑包含脚本元素的DOM元素(或更具体地说,在元素的用于引起大问题的结束标签/ a>在IE6(感谢 TJ Crowder )和IE7。

However, keep in mind editing a DOM element which contains a script element (or more specifically, before the element's closing tag) used to cause big problems in IE6 (thanks T.J. Crowder) and IE7.

但是,这需要内联脚本,这可能是一个维护问题。最好将JavaScript存储在外部(许多人在关闭正文标签之前说出包含它们的好处),这有很多好处,如易于维护和细粒度缓存控制。

However, this requires inline scripts which can be a maintenance problem. It is preferred to have your JavaScript stored externally (and many speak of the benefits of including them before the closing body tag) for many benefits such as ease of maintenance and fine grained cache control.

这篇关于是否真的有必要等待DOM准备好操纵DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆