I have some JavaScript (code to initialize Google Maps if you’re interested) that I’m forced to include within the <body></body> tags of an html document and I would like to have one of my methods trigger on page-load complete. The catch is that I don’t have access to the <body> html tag, so I can’t do:
<body onload="foo()">
Is there any way to accomplish this? I realize this is a ridiculous scenario.
Depending on when the code is run, attach the handler with JavaScript:
As you seem to have no control over the page we have to be a bit more careful. Other JavaScript might already have set an event handler. To be a good citizen, we don’t just overwrite the event handler, but keep a reference to it in case it exists.
However other JavaScript code could overwrite this again.
The best way would be to use the more advanced event handling methods
addEventListener(W3C) andattachEvent(IE).For more information about event handling I suggest to read the excellent articles on quirksmode.org.