Skip to content

Instantly share code, notes, and snippets.

@HereChen
Forked from tao4yu/window_onLoad.js
Last active August 29, 2015 14:28
Show Gist options
  • Save HereChen/d99ec2f35f826ffd1f21 to your computer and use it in GitHub Desktop.
Save HereChen/d99ec2f35f826ffd1f21 to your computer and use it in GitHub Desktop.
Javascript : window.onload 绑定多个事件
/*
*假设有2个函数firstFunction和secondFunction需要在网页加载完毕时执行, 需要绑定到window。onload。如果通过:
*
* window.onload = firstFunction;
* window.onload = secondFunction;
* 结果是只有secondFunction会执行,secondFunction会覆盖firstFunction。
*/
/*
*正确的方式是:
* Javascript 共享onload事件处理方法:
*/
//1.在需要绑定的函数不是很多时,可以创建一个匿名函数容纳需绑定的函数,再将该匿名函数绑定至window。onload函数
window.onload = function()
{
firstFunction();
secondFunction();
}
//2.实现一个函数addLoadEvent,如下
function addLoadEvent(func)
{
var oldOnLoad = window.onload;
if(typeof window.onload != 'function')
{
window.onload = func;
}
else
{
window.onload = function()
{
oldOnLoad();
func();
}
}
}
addLoadEvent(firstFunction);
addLoadEvent(secondFunction);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment