The way you've written your code, it's not running onload, it's just running when the parser hits it. Because you wrote getLocation()
rather than just getLocation
, it executes the function.
If you are certain there will be nothing else to be fired on load, you can do window.onload=getLocation;
. If you want to make sure you play nicely with other code (including third-party frameworks/libraries) that might use the load event, you can do something like this:
window.addEventListener('load', getLocation);
Note that that code won't work in IE8. If you need to support IE8, check for addEventListener()
and if it is not found, check for and use attachEvent()
instead:
if (window.addEventListener) {
window.addEventListener('load', getLocation);
} else if (window.attachEvent) {
window.attachEvent('onload', getLocation);
} else {
window.onload = getLocation;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…