javascript conflict multiple body onload events needs to be first in row
I have multiple javasripts that needs using body onload event
It should be simple solution for that - just add all events in row like this:
<body onload="showContent();
randomImages();
placeIt();
showIt();
preloadImgs();
initialize()">
But of course life isnt so simple..
fore some reason some scripts needs to be FIRST in row. So if I put showContent();
first, randomimages wont execute and vice versa.
I also tried replace onload event with script like this
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", showContent, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", showContent );
}
else {
if ( window.onload != null ) {
var oldOnload = window.onload;
window.onload = functi开发者_开发问答on ( e ) {
oldOnload( e );
showContent();
};
}
else
window.onload = showContent;
}
So far I have no solution for this conflict. Does somebody have good idea?
Why not create another function that holds all those functions and then call that one function on load? This is assuming your functions doesn't have some dependencies from the other functions.
showContent();randomImages();placeIt();showIt();preloadImgs();initialize()
can be in a bit more organized location:
function Init()
{
showContent(); // if this errors out, execution for the rest stops
randomImages();
placeIt();
showIt();
preloadImgs();
initialize();
}
@Felix Kling you are partly right, they are initiated sequentially but the execution time of each function will be different, therefore it is possible to create a race condition where the last function in the sequence could complete before the first one in the sequence completes.
The answer to this question is to build in callback into your functions. Then you can sequence them and the subsequent function will be called only when the prior one completes. There's a pretty good answer on that subject here.
However I have another point. Try to avoid using the Body Onload combination, and instead use Jquery's document .ready() function. This is because the Body Onload can fire before everything has been loaded - I think this is explained better on the JQuery website here.
精彩评论