如何以跨浏览器的方式使用JS附加一个事件?就像这样简单?
document.body.onload = function(){
alert("LOADED!");
}
如何以跨浏览器的方式使用JS附加一个事件?就像这样简单?
document.body.onload = function(){
alert("LOADED!");
}
为什么不使用 window
自己的 onload
事件?
window.onload = function () {
alert("LOADED!");
}
如果我没记错的话,它在所有浏览器中都兼容。
这利用了DOMContentLoaded - 在onload之前触发 - 但允许您插入所有不引人注目的内容...
window.onload - Dean Edwards - 博客文章中有更多相关信息 - 这里是从同一博客评论中复制的完整代码。
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
跨浏览器的window.load事件
function load(){}
window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )
document.body.onload
是一种跨浏览器的,但是遗留机制,它只允许一个回调函数(你不能将多个函数分配给它)。
最接近的“标准”替代方法是 addEventListener
,但它不受 Internet Explorer 支持(它使用 attachEvent
),因此你可能希望使用库(jQuery、MooTools、prototype.js 等)来为你抽象出跨浏览器的丑陋细节。
jcalfee314的想法对我很有帮助 - 我原本有一个window.onload = onLoad
,这意味着<body onload="...">
中的函数没有被调用(我无法控制)。
这个方法解决了问题:
oldOnLoad = window.onload
window.onload = onLoad;
function onLoad()
{
oldOnLoad();
...
}
编辑:Firefox不喜欢oldOnLoad = document.body.onload;
,所以替换为oldOnLoad = window.onload
。
对于不同的浏览器,您需要使用几种不同的方法。像jQuery这样的库为您提供了一个跨浏览器接口,可以为您处理所有这些。
为什么不使用jQuery?
$(document).ready(function(){}))