Back Button/Onload Mess
Working on some code earlier this week, I discovered that Opera doesn’t fire the
load event when navigating to a page using the back button. This means anything set to fire
onload doesn’t get executed…so much for good coding practices. But this issue appears to intermittently happen on other browsers too, notably Firefox and Safari (Internet Explorer fires
load no matter what).
Really, there should be some standard way of determining when the DOM document has been completely created and is ready to be used versus the
load event, which only tells us after everything on the page has been loaded. (This is where the YUI‘s onAvailable() method comes in really handy.) There actually are a mishmash of ways to do this otherwise, but no way that is common across all browsers:
- Using the
defer) only works for external files, not inline scripts).
- Use the document’s
DOMContentLoadedevent. This is supported by Firefox and Opera (starting in version 9). This event fires when the document is completely loaded. I can’t find anything saying that this is a standard right now, but it works.
- Internet Explorer’s
documentobject supports a
readystatechangeevent that fires whenever the document’s
readyStateproperty changes. This is different from using an XML DOM object in that it returns strings…you want to look for “complete” as a value to determine when the DOM is ready for manipulation.
- Apparently, Safari supports the
readyStateproperty on a document but has no event for watching it, therefore you could set a timeout to watch for it to change.
- Dean Edwards also suggests another approach using Internet Explorer’s behaviors.
All of this adds up to major pain in the butt. Then again, I just keep telling myself, all of these differences is why people like me have jobs. If it all worked the same everywhere, we’d have far less value than we do.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.