Reputation: 1456
I am trying to call three JavaScript functions during body onload.
<body onload="initializeb(); initializec(); initialize();">
For some reason it is only calling the first two and then not even calling the third function.
Will someone please enlighten me why this is failing after the second function?
Upvotes: 0
Views: 358
Reputation: 6468
I would recommend consolidating all your initializing functionality into one initialize()
function, much like the user Ramesh Kotha pointed out:
<body onload="initialize();">
function initialize(){
initializeA();
initializeB();
initializeC();
// other init tasks ...
}
But it should be added, that body onload
can sometimes be problematic if you are trying to support older browsers (especially older versions of IE or Safari), so I wanted to add that if you are using jQuery in your application, then you can use jQuery's $(document).ready()
handler to load any of your init functions after the DOM is ready (which is essentially what is happening with body onload, without all the hassle), so this code is functionally equivalent to the above code:
// Example using jQuery's .ready() function
$(document).ready(function(){
initializeA();
initializeB();
initializeC();
// other init tasks ...
});
The reason why one of the functions isn't being called is most likely due to an error in the function. Just put a console.log()
statement at the top of the function you think isn't working and check the console for output:
function initialize() {
console.log("initialize function has been called");
}
Hope this helps.
Upvotes: 2
Reputation: 2261
What about using eventlistener? like this:
if (document.addEventListener) {
window.addEventListener("load", initializeA);
window.addEventListener("load", initializeB);
window.addEventListener("load", initializeC);
}
else if (document.attachEvent) {
window.attachEvent("onload", initializeA);
window.attachEvent("onload", initializeB);
window.attachEvent("onload", initializeC);
}
else {
window.onload = function() {
initializeA(), initializeB(), initializeC()
};
}
Upvotes: 1
Reputation: 8322
its better to have a common function initialize()
and call all the remaining functions from that
<body onload="initialize();">
function initialize(){
initializeb();
initializec();
initialized();
}
Upvotes: 4