Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - Is it really necessary to wait for DOM ready to manipulate the DOM?

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?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...