Do you really need to wait until the DOM is ready to manipulate the DOM?

Do you really need to wait for "ready" (or "window.onload") events if your code only controls DOM elements that have already been parsed entirely?

The jQuery documentation for the ready () function demonstrates how you can wait for the action to complete until the DOM is completely ready, but for example, for the code (script tags) that are listed before the corresponding DOM elements. But it seems that the code that appears after the necessary DOM elements in the HTML document has access to them, because, presumably, the DOM is created when the browser parses the document.

For example, is it possible to assume that the following code is reliable in all situations or is it still necessary (or useful in some way) to use the 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 raise it to find out if there is any information.

+4
source share
4 answers

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

However, keep in mind editing the DOM element that contains the script element (or, more specifically, before the element’s closing tag) used to cause big problems in IE6 (thanks to TJ Crowder ) and IE7.

However, this requires built-in scripts , which can be a maintenance problem. It is preferable that your JavaScript be stored externally (and many talk about the benefits of including them before the closing body tag) for many benefits, such as ease of maintenance and fine-grained cache control.

+6
source

in your case, this is fine, because the browser will display your code line by line, and in your code id = "foo" in the first place, so it will get this div .... but suppose you wrote this script in your head tag, then the script will work first, and it won’t get the div with id = "foo" because it is not loaded yet. Better to write in the document.ready method

+1
source

Yes, it is safe if you use js code after dom, but usually it is not a good idea to mix html and js.

0
source

The document is loaded linearly, so your code is working correctly. Sometimes programmers do not use a document ready to achieve the goal when javascript is not dependent on the DOM below. The following is an example.

0
source

All Articles