I have an issue with DOMnode.getBoundingClientRect() because the data returned is not consistent. I am using windows.onload
(for the lack of a better option) to trigger my function which takes a getBoundingClientRect().height
of an element to do some calculation with it.
Issue is, the height of the element is not always consistent. window.onload
even should fire last in the page lifecycle as far as i know and both the content and the stylesheets and external resources should be loaded by then, however the page apparently still hasn't rendered it properly yet since I sometimes get height values of like 400, 528, 630 and sometimes its correct (700) for an element I am trying to read.
Thoughts?
Is there some other way to detect when the a div
(or a page) has had itself rendered fully?
I have an issue with DOMnode.getBoundingClientRect() because the data returned is not consistent. I am using windows.onload
(for the lack of a better option) to trigger my function which takes a getBoundingClientRect().height
of an element to do some calculation with it.
Issue is, the height of the element is not always consistent. window.onload
even should fire last in the page lifecycle as far as i know and both the content and the stylesheets and external resources should be loaded by then, however the page apparently still hasn't rendered it properly yet since I sometimes get height values of like 400, 528, 630 and sometimes its correct (700) for an element I am trying to read.
Thoughts?
Is there some other way to detect when the a div
(or a page) has had itself rendered fully?
1 Answer
Reset to default 5window
's load
does indeed mean all resources (including stylesheets and images) have either loaded or failed, but:
- It doesn't necessarily mean the browser has pletely rendered the result, and
- If other JavaScript code is running on
load
and changes things, those changes may also impact what you're seeing (of course)
Solving #2 will be specific to the code running, but if your problem is just #1, a short setTimeout
should fix it:
window.onload = function() {
setTimeout(function() {
// Your code here
}, 60);
};
You may have to play with the delay. 0 tends to work for Chrome, but Firefox tends to want values in the at least 50-60ms range.
Or possibly just requestAnimationFrame
may be sufficient:
window.onload = function() {
requestAnimationFrame(function() {
// Your code here
});
};
You might bine one or the other of the above with a check that document.readyState
is "plete"
, since that's the very last thing the browser does (other than JavaScript code set to run on pletion, of course). So for instance:
window.onload = function() {
function ready() {
// Your code here
}
function checkReady() {
if (document.readyState === "plete") {
ready();
} else {
setTimeout(checkReady, 0);
}
}
};