Reputation: 19
what's the difference between putting all codes inside the window.onload=function(){}; and putting only the function name inside the window.onload=function(){};?
putting all codes inside the window.onload:
window.onload=function() {
function(){
// do something here
}
};
putting only the function name inside the window.onload:
function foo() {
//do something here
}
window.onload=function() {
foo();
};
what's the difference? or is there any difference between them?
Upvotes: 0
Views: 84
Reputation: 109
First thing , You can't declare function inside function . As you first did ,
You can write some query inside function. But if you want use your query again
and again then you have to declare a function and you will put your query.
Then you will call that function from other function inside the same page.
Upvotes: 0
Reputation: 475
It is very similar!
In the first case you declared a function only when window.onload
is fired.
In the second case you declared a "globally" function accessible from window.onload
event
See this plunker demo: demo
Upvotes: 1
Reputation: 8354
In the first case all your code in centralized in a anonymous function ,which is good since you aren't polluting the global namescpace.
In the second case , foo
will be available globally in your js ,which could cause a clash if you or someone using your js file redefines foo
Upvotes: 0
Reputation: 22158
If you declare it inside the window.onload
, you only be able to use it when window.onload
fires, not before. If you need to use the function before than hole document is loaded, you can't. Otherwise, if you write the function outside, you only call it when the event fires, but you can use it as soon as be defined.
Upvotes: 2