I have couple of functions that should be triggered after some delay in onload event. It works fine in chrome but not in Firefox.
function foo() {
// javascript code
}
window.onload = setTimeout(foo, delay);
function bar() {
// javascript code
}
window.onload = setTimeout(bar, delay);
If I remove the delay, 'bar' gets invoked in Firefox and 'foo' and 'bar' get invoked in chrome. What could be the issue here?
No, there isn't a way to delay the window onload. You could try to add a lot of images and other things that take a long time to load, but that's not an ideal solution. Instead, you can use setTimeout to make code run after a period of time. setTimeout(function(){ window.
onload = function() { yourFunction(param1, param2); }; This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
The onload executes a block of code after the page is completely loaded while $(document). ready(function) executes a block of code once the DOM is ready.
I'm surprised both functions get invoked in any browser. But you might have better luck with something like:
function foo() {
// javascript code
setTimeout(bar, additionalDelay);
}
function bar() {
// javascript code
}
window.onload = function() { setTimeout(foo, delay); };
Edit: Nevermind, I see why both of the timeouts execute. When you do something like:
window.onload = setTimeout(bar, delay);
...you are not actually setting window.onload
to execute your function after a delay. Instead this is immediately invoking setTimeout()
to schedule your function call, and assigning the result (a handle to the scheduled function invocation) to window.onload
. This is not correct, and will probably cause a runtime error in some browsers when they try to invoke window.onload
as a function.
What you want to do instead is assign a function to window.onload
, like:
window.onload = function() {
setTimeout(foo, delay);
setTimeout(bar, delay);
};
You could use jQuery with sth like that:
$(document).ready(function() { /* your code */ });
or
$(window).load(function() { /* your code */ });
jQuery automatically adds functions to stack, and run them all once event is triggered.
If you want do it with only JS, you can make array of functions to trigger:
function a() {
alert('a');
}
function b() {
alert('b');
}
var arr = new Array(a, b);
window.onload = function() {
for(var i = 0; i < arr.length; i++) {
setTimeout(arr[i], 1000);
}
}
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With