What is the DOM ready event?

梦想的初衷 提交于 2019-11-26 16:08:31

问题


I need to fire a script as soon as the page content (the whole HTML element) has been received, but it doesn't have to be rendered yet.

I assume that just having a simple <script> tag that executes some code at the very top of my page should do the trick?

To formulate the question differently: does DOM ready mean that all elements and resources have been pulled and rendered?


回答1:


DOM ready means that all the HTML has been received and parsed by the browser into the DOM tree which can now be manipulated.

It occurs before the page has been fully rendered (as external resources may have not yet fully downloaded - including images, CSS, JavaScript and any other linked resources).

The actual event is called DOMContentLoaded.




回答2:


DOMready means: The DOM structure has been built in browser memory. Asynchronously the page already started rendering, but it might not be finished yet as external resources like images, videos etc. will finish loading later.




回答3:


You might also try with the functions

window.onload = function(){
   //your code
  }

or

body.onload = function(){
   //your code
  }

if you don't want to use jQuery.

Be careful though, DOM loaded doesn't mean the page loaded, iframes, javascript, images and css might load after that event.

There is a good tuto on DOM events Javascript tutorial




回答4:


I need to fire a script as soon as the page content (the whole HTML element) has been received, but it doesn't have to be rendered yet.

I assume that just having a simple tag that executes some code at the very top of my page should do the trick?

It's likely then that you want the DOMContentLoaded event. You can use it thusly:

    <head>
    <!-- … --->
        <script>
window.addEventListener('DOMContentLoaded',function () {
    //your code here
});
        </script>
    </head>

To formulate the question differently: does DOM ready mean that all elements and resources have been pulled and rendered?

There is no "DOM ready" event. You're probably thinking of jQuery's .ready(), or some similar odd use of this terminology (e.g. Google also has a similarly named proprietary event they refer to).

For the DOMContentLoaded event, however (to quote MDN):

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.




回答5:


The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.[1] The nodes of every document are organized in a tree structure, called the DOM tree



来源:https://stackoverflow.com/questions/12637725/what-is-the-dom-ready-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!