简体   繁体   中英

How to know when an Html Element is ready (rendered)?

I have some javascript that adds an element to the document. Immediately after adding i am trying to obtain the element's clientWidth and clientHeight. However I am seeing all properties related to size to be 0. But at a later point i notice that the size properties do get populated with actual size values (eventually).

How can I know when the size details are available for an added Html element? I have tried listening to various events, such as onload and onreadystatechange. However these events seem to only apply for the document itself, not for individual elements.

Thanks much.

DOM changes are postponed until the javascript thread quits, therefore this doesn't work:

someNode.addChild(someElem);
w = someElem.clientWidth // 0

You have to start a new thread in order to work with newly added element:

someNode.addChild(someElem);

setTimeout(function() {
     w = someElem.clientWidth // should work
}, 0)

Alternatively (and better), try listening to a DOM mutation event:

document.body.addEventListener('DOMNodeInserted', function(e) {
    alert('div height=' + e.target.clientHeight)
})

d = document.createElement("div")
d.appendChild(document.createTextNode("hello"))
t = document.body.appendChild(d)

http://jsfiddle.net/rM5cJ/

You could set an initial dictionary (object literal can be used)— where you set at the very first start of the document , and after each html being rendered you can do :

<div id='aaa'> </div>

<Script>myObject.Add('aaa',1,doSomethingLater) </script>

You can not use the onload event since it's relevant only for : img / body/iframes.

The object can look like this :

myObject =
{
 Add:function (a,b,cb){this[a]=b;cb(a,b)} 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM