Is there a way to attach event handlers to an HTML element as soon as the element is present on the page.

StackOverflow https://stackoverflow.com/questions/19969553

Pergunta

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.

Foi útil?

Solução

Three ideas:

  1. Use an attribute in the HTML like onclick="foo()". This will be in force immediately.

  2. 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.

  3. 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: visible after 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.

Outras dicas

you have to wait until document.body is rendered.

after that anything could be done like this

var ele = document.createElement("div");
ele.onclick = function(e){...};
document.body.appendChild(ele);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top