I have one paragraph of javascript code. And i don't understand it very well. Can you expain it line by line for me? Thanks a lot.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
And here is what i'm thinking:
function addLoadEvent(func) { //define a function with a parameter 'func'
var oldonload = window.onload; //assign window.onload event to variable oldonload
if (typeof window.onload != 'function') { //if window.onload is not a function, then...
window.onload = func; //assign 'func' to window.onload event. what does func mean?
} else { //if window.onlad is a function
window.onload = function() { //don't understand
oldonload(); //call function oldonload()
func(); //call function func()
}
}
}
Confusions:
window.onload is already an event, and why do we use typeof?
function addLoadEvent(func) , window.onload = func, func(). What's the difference among these funcs?
I'm sorry for posting a novice problem. But thanks to anyone who gives me some guidance?
Edit:
This is improved original code by Simon Willison.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}