Skip to content

Instantly share code, notes, and snippets.

@tao4yu
Last active June 5, 2017 01:45
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tao4yu/9599517 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);
@XuDongling
Copy link

为什么我这样写之后显示window为定义?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment