Safely query size of element soon after inserting it to DOM

69 Views Asked by At

Is there an way (maybe an event?) to delay querying the height of element until all of the styles for it have been fully calculated, so that I know that it's height is calculated properly?

In my app I need to get the height of an element as soon as possible. I run that calculation soon after it's been inserted into DOM (using MutationObservers for detecing that). Still some (not all) of the results are incorrect - the height is different (higher) than what I see in the end in my browser. If I delay the calculation by 200ms using setTimeout, the results are corrent though.

Is there some cleaner solution to that, without using setTimeout? That one is a bit hacky (including the fact 200ms works in my browser doesn't mean that it'll work in all others and I can't increase it - I need to do that calculation as soon as possible).

1

There are 1 best solutions below

3
On BEST ANSWER

You can use the onload event which fires after everything in the document has been completely loaded.

You can use it in your markup like this:

<body onload="doStuffAfterEverythingIsLoaded()">...</body>

or in your script:

window.addEventListener("load", doStuffAfterEverythingIsLoaded);

Hope this will help.