用 JS 附加一个 body onload 事件 [英] Attach a body onload event with JS

查看:27
本文介绍了用 JS 附加一个 body onload 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以跨浏览器的方式使用 JS 附加 body onload 事件?就这么简单?

How do I attach a body onload event with JS in a cross browser way? As simple as this?

  document.body.onload = function(){
      alert("LOADED!");
  }

推荐答案

这利用了 DOMContentLoaded - 它在加载前触发 - 但允许您保持所有不显眼...

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - 博文详细介绍了它 - 这是从同一博客的评论中复制的完整代码.

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// 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;

这篇关于用 JS 附加一个 body onload 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆