Reputation: 4277
Preface
Please note that word stable in question below does not refer to some specific coined industry term (I work with js for last 5 years and haven't heard of term "stable DOM" so assume that there is no such thing). Also this doesn't refer to specification. Stable means - no reflows or repaints are being done at the moment and no scheduled.
Question
How to check if DOM tree / page is stable after some javascript that triggers repaint/reflow (see here for examples of reflow/repaint )
Is there some (browser
, window
, DOM
etc.) event I can addEventListener
to?
Maybe there is some strange way to do this like putting my code I need to run as a callback function to some function like requestAnimationFrame()
?
My set up (I believe the question is enough detailed with only text above, but people asked for my set up)
I have React application. In one place I am using .offsetTop
recursively to find offset of the few components from the page body in componentDidMount
method. Namely with this function, where I pass 4 elements found by document.getElementById()
findPosY = obj => {
let curtop = 0
if (typeof obj.offsetParent !== 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop
obj = obj.offsetParent
}
curtop += obj.offsetTop
} else if (obj.y) {
curtop += obj.y
}
return curtop
}
This function return for 2 of those elements the same height. But if I do calculations after 100ms
everything works perfectly.
In other component I'm doing some interaction using js with inline styles of rendered html that can happen during rendering.
UPDATE 1. DOMContentLoaded
won't aid here. Running height calculation as
document.addEventListener('DOMContentLoaded', () => {
// call appropriate function
})
doesn't provide desired result.
Upvotes: 0
Views: 360
Reputation: 32063
I don't think there's any such thing.
If there's any "reflow scheduled", offsetTop
must stop until the reflow is done and only return a value once "in stable condition", so I'm not sure how such a thing would help you even if it existed.
Check what leads to the differences you're observing between an immediate and a delayed execution. If that doesn't help, create an MVCE, maybe it'll turn into a useful bug report for the browser you're testing with.
Upvotes: 1