1

My load events do not always fire in safari or chrome on mac (safari version 7.0.5, chrome version 43.0.2357.124). It works fine in firefox and in any of my windows browsers.

window.addEventListener('load', function (){
    alert("loaded js");
}, false);

$(window).bind("load", function() {
    alert("loaded jquery");
});

Both functions fire or none of them does.

Does someone know what is happening here?

Thanks for help.

Palo
  • 373
  • 1
  • 12

1 Answers1

2

Since that JS is in a separate file, I can imagine that at the time it runs, the load event has already been fired.
You can detect this, however, using document.readyState (see also this question).
It has three possible values:

  • loading - parsing is still going on
  • interactive - parsing has finished, but resources are loading
  • complete - pasing has finished and resources have been loaded

I suggest you check whether document.readyState == 'complete' and run your code, otherwise register an event listener:

~function()
{
    var loadJS = function()
    {
        alert("loaded js");
    };
    var loadJQ = function()
    {
        alert("loaded jquery");
    };
    if(document.readyState == 'complete')
    {
        loadJS();
        loadJQ();
    }
    else
    {
        window.addEventListener('load', loadJS, false);
        $(window).bind('load', loadJQ);
    }
}();
Community
  • 1
  • 1
Siguza
  • 21,155
  • 6
  • 52
  • 89