I do not want to wait till the whole HTML DOM is ready. Note that I’m not talking about dynamically loaded HTML elements. I’m talking about element which are in the HTML but not rendered yet.
Use an attribute in the HTML like
onclick="foo()". This will be in force immediately.
You could place a
<script>tag immediately after the HTML element embedded in the HTML and have that script add the event handler. All DOM elements located before a script are guaranteed to be parsed and ready.
You could make the element by initially hidden (either inline style specification or CSS), then wait until it’s in the DOM, run your script to install the event handler and then make the object visible. If you use
visibility: hidden, then the document will lay out as normal and the content can be made
visibility: visibleafter installing the event handler.
The browser doesn’t offer access to the object until it’s parsed and in the DOM so any script that wants to operate on it has to either be physically located after the DOM element or has to wait for an event to occur that indicates the DOM has been loaded.
The browser doesn’t offer an event when a DOM element is parsed, but not yet visible that would offer you a chance to operate on it at that moment so you have to work around your issue with one of these other methods.
Answered By – jfriend00