Does this code need to be in a document.ready?

前端 未结 7 2069
清酒与你
清酒与你 2020-12-28 13:09

The document.ready is used to execute code after the DOM is fully loaded. This can be used to attach event handlers to elements on the page e.g



        
7条回答
  •  有刺的猬
    2020-12-28 13:51

    1. When binding event handlers to the document itself, is it necessary to put that code in a document.ready?

    No. In fact, the 'on' methods for binding in JQ can delegate at the document so you could use those at any time on any element safely as long as there wasn't a lot of bubbling being stopped at container elements with stopPropagation.

    2. Are there any downsides to not wrapping the code in the document.ready?

    Only that scripts in the head might try to hit HTML that isn't there yet. The converse is that HTML might be ready and getting events from the user before the doc is. See 'on' methods or google 'event delegation' for having your cake and eating it too where events are concerned (the caveat is libraries that use stopPropagation stupidly). document.ready is mostly just a way to be certain your code is firing when the HTML is ready to be hit. It's not necessary for code that falls at the bottom of the body tag unless (maybe) you're hitting body itself with something.

    3. What sequence of events take place when the document is being constructed, right before the document.ready is fired ?

    At the point that document ready is fired, all tags have been parsed and the layout dimensions have been established. Images do not need to have fully loaded, and I'm only guessing, but I suspect non-layout impacting CSS may not be in effect yet in some browsers. An element is considered 'ready' when its closing tag has been read and executed on by the HTML parser. JS in script tags must be handled by an interpreter before HTML parsing can continue, which is why we tend to put our code at the bottom of the doc nowadays anyway, for faster perceived loading time.

提交回复
热议问题