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();
}
}
}
Its very simple.
You check if there is already an onload function registered.
if there isnt one,
1. assign ‘func’ the function you pass in to the onload
if there is one,
create a new onload function, that will:
and:
window.onload can be a function, but if one isnt set, it will be ‘undefined’ we need to check its type to see what it is.
functions are a variable in javascript. so you can refer to the function as
func
you can call it as
func()
in your case: function addLoadEvent(func) is the current function defintion. it takes one param, and that param should be a function
window.onload = func
assigns the function you passed in to the onload event
func()
calls the function you passed in
here is the line by line correction: