
Let’s talk JavaScript. You all know about the « onload » event which is triggered when a page is fully loaded, right?
And if you use JavaScript frameworks such as jQuery or MooTools (or others), it’s most likely you also heard about the « onready » event. It’s triggered earlier, when all DOM elements are here an ready to rock, but before things like scripts, images and iframes are fully loaded, buying you some precious time to run your JavaScript.
It’s pretty nifty, and i use « onready » all the time instead of « onload ». Or at least i used to.
Today i stumbled upon a mysterious bug : i was storing one element’s top offset while listening to the « onready » event, and the stored value kept changing between the correct one and a coming-from-outer-space other.
And as i kept refreshing the page, i could see those values appearing and disappearing, like if they were playing hide and seek with me. Enough BS, i started thinking, and eventually found out that when the bad value was coming up, the page was taking an average longer time to load than usual.
This made me think i had some fixed positioned elements on the page, and that as long as the stylesheet wasn’t fully loaded, they were « position: static » for all the browser knew. Meaning their height was taken into account -instead of being null- when computing the offset of an element underneath.
At this point, it was pretty clear that the CSS not being fully loaded before running my JavaScript was the reason it was failing. Thus, running it « onload » instead of « onready » magically solved the problem, since the JavaScript was being executed once all elements’ real dimensions were set.
The one thing to remember here is as follows :
When your JavaScript makes use of elements’ dimensions, wait for the page AND all resources to be fully loaded : use « onload », not « onready »!