Skip to content
Advertisement

Having an issue when using load events on firefox and safari

Both firefox and safari refuses to execute load event when loaded from an external js file. It only works on google chrome.

I can’t really understand the problem.

in my html :

<script src="/assets/js/pages/myFile.js" type="text/javascript"></script>

in myFile.js :

window.addEventListener("load", function(event){
// do someting (only works in chrome browser)
})

My html page is serverd by node.js (ejs page), myFile.js is recognized by the 3 browsers (Firefox, chrome & safari), so I don’t really understand why my load event fail with ff & safari.

I’ve also tried window.unload unsuccessfully.

Any suggestion ?

Advertisement

Answer

Seems like event is already fired, I’m suggest to always check for it:

function onLoad(callback){
    if (document.readyState === 'complete') {
        callback();
    } else {
        window.addEventListener("load", callback);
    }
}

onLoad(function(){
    // do someting
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement