本文介绍了用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 - 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事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:18