开发者

Are an element's dimensions readable immediately upon adding it to the DOM tree?

Suppose I dynamically create a DIV using document.createElement, add some inner text, and want to determine its height and width. I can see that before adding the DIV to the DOM tree, properties such as offsetWidth and offsetHeight are 0, which is expected. Once it is programmatically added to the tree, can I expect those properties to be immediately "ready", or are there environments where repaint/reflow may be delayed and occur later?

textDiv = document.createElement("div");
textDiv.innerHTML = "some dynamically created string";
console.log(textDiv.offsetWidth); // 0
document.body.appendChild(textDiv);
console.log(textDiv.offsetWidth); // OK?

I think the answer would be something like "the JavaScript interpreter is single-threaded and the repaint/reflow event triggered by appendChild is part of that thread and finishes before continuing on to the next statement"... but can someone check my understanding?

This Opera article has a 开发者_如何转开发lot of what I'm looking for but it's not clear how Opera-specific it is. In any case it does seem like the application developer can assume any required repaint/reflow correctly occurs when taking measurements such as by accessing offsetWidth.


As soon as your element is added to the DOM, it should be available for access as if it were there from the beginning. Plain, simple DOM manipulation is synchronous.

Be careful when you start introducing timeouts, intervals, and Ajax.


As far as i know, they are readable only after they are added to DOM tree after all javascript functions or properties work on elements that are already there in the DOM tree.

I tried both cases and following turned out to be working fine:

<SCRIPT>
window.onload = function() {
textDiv = document.createElement("div");
textDiv.innerHTML = "some dynamically created string";
alert(textDiv.offsetWidth); // 0
document.body.appendChild(textDiv);
alert(textDiv.offsetWidth); // OK?
};

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜