3

I have some web pages which rely on body.onload (or, equivalently, window.onload) to set them up properly. Sometimes onload is not being called.

Is there a trick with some web browser (ideally Chrome, where this apparently happens most often) which will tell me what exactly is preventing the page from loading successfully?

Clue: this rarely (maybe even never) happens when I hit F5 to reload the whole page, but more generally it happens if a page has been arrived-at by clicking a link or pasting the url into the address bar. Is there a quirk of onload semantics that might be tripping me up?

N.B. The scripts themselves are not producing any errors in the console.

spraff
  • 32,570
  • 22
  • 121
  • 229
  • *"I am happy to accept a "don't-use-onload" solution provided that I can hook into a cross-platform event which happens after the DOM is fully loaded."* If you're in control of where your script tags go, just put them at the bottom of the page. – T.J. Crowder Nov 08 '12 at 17:31

2 Answers2

3

I think you want window.onload

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • Apparently they are [the same event](http://stackoverflow.com/questions/191157/window-onload-vs-body-onload) and when I experimented that didn't fix it. I still need to find out why the page isn't loading. – spraff Nov 08 '12 at 17:37
  • Yes `onload` is the same event, but attaching it to `window` vs. `body` is _not_ the same. That said, sounds like you have something else going on. What's your JS console say? – Madbreaks Nov 08 '12 at 17:38
  • As stated in the question, the console is empty. – spraff Nov 08 '12 at 17:41
1

I have tested such cases, and none of the following will work:

var callback = function() { alert("Body loaded"); };
$("body").load(callback);
document.body.addEventListener("load",callback,false);

However, document.body.onload seems to work fine. Make sure that body is correctly namespaced:

document.body //<body>
body //Reference error

If you're talking about:

<body onload="callback();"></body>

Then go back and review your code, because it should work.


Personally, I suggest using the load event of the window object or a framework's ready event.

//Execute when the window is loaded
var callback = function() {
     //Your code goes here...
};
if (window.addEventListener) window.addEventListener("load",callback,false);
else window.attachEvent("load",callback);

With jQuery, you only need the following:

$(window).load(callback);

jQuery's ready event is as follows:

$(document).ready(callback);
//Or just:
$(callback);

MooTools use this:

window.addEvent("domready",callback);

And different libraries all have their own way.

MateyY
  • 184
  • 4