I have some code that looks like this
//create a long string of html, which includes a div with id="mydiv"
someElement.innerHTML = s; //s is the string above
document.getElementById('mydiv')
Now, after I set the innerHTML, it is going to take a while for the browser to actual render the DOM that includes id="mydiv" . So, will the javascript sit and wait for the dom to be properly rendered after the innerHTML injection, or will it move right along and call the getElementById which is now unsafe since the DOM for that id may not be created yet?
I have some code that looks like this
//create a long string of html, which includes a div with id="mydiv"
someElement.innerHTML = s; //s is the string above
document.getElementById('mydiv')
Now, after I set the innerHTML, it is going to take a while for the browser to actual render the DOM that includes id="mydiv" . So, will the javascript sit and wait for the dom to be properly rendered after the innerHTML injection, or will it move right along and call the getElementById which is now unsafe since the DOM for that id may not be created yet?
Share Improve this question asked Jan 12, 2011 at 2:55 Joda MakiJoda Maki 5,8696 gold badges31 silver badges37 bronze badges 2- javascriptkit./dhtmltutors/domready.shtml – Eric Fortis Commented Jan 12, 2011 at 2:57
- Do as patrick says and try it. I expect it to work just fine. – Hemlock Commented Jan 12, 2011 at 3:01
2 Answers
Reset to default 5Here's an example that inserts nearly 12,000 elements into the DOM using innerHTML
, then calls getElementById()
to find the one element at the end that has an ID.
It successfully finds the element.
Example: http://jsfiddle/fzUUU/
There is no standard for innerHTML. So literally anything is allowed to happen including not being implemented (I believe Opera toyed with this once). It's just a hack introduced by Microsoft in IE.
However. Implementing innerHTML in any way that diverges from the way IE does it will break lots of pages on the web. So browser makers are forced to implement it the way IE does it. And here's how IE does it: when innerHTML is running the script interpreter stops. That is to say innerHTML blocks until the DOM is fully parsed.
So it should be safe to access the DOM directly after innerHTML for all current browsers and, due to the number of pages on the web that requires it, in the foreseeable future.
Additional answer:
It appears that the draft HTML5 spec specifies innerHTML: http://www.w3/TR/2008/WD-html5-20080610/dom.html#innerhtml0
It basically describes what IE already does. It should be noted that it doesn't specifically say weather the operation is bolcking or non-blocking but as mentioned earlier a non-blocking implementation will break lots of pages on the web.