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

前端 未结 4 751
北海茫月
北海茫月 2020-12-11 08:03

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

相关标签:
4条回答
  • 2020-12-11 08:35

    Document is loaded in linear fashion so your code works correctly. Sometimes programmers do not use document ready for performance purpose when the javascript is not depends on the DOM below it. Here is some example.

    0 讨论(0)
  • 2020-12-11 08:37

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

    0 讨论(0)
  • 2020-12-11 08:38

    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.

    0 讨论(0)
  • 2020-12-11 08:46

    in your case it is fine because the browser will render your code line by line and in your code id="foo" comes first so it will get that div....but suppose you wrote this script in head tag then the script will run first and it wont get the div with id="foo" because its not yet loaded..its better to write in document.ready method

    0 讨论(0)
提交回复
热议问题