Attach a body onload event with JS

2019-01-04 01:20发布

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!");
  }

7条回答
不美不萌又怎样
2楼-- · 2019-01-04 01:27

Why not using jQuery?

$(document).ready(function(){}))

As far as I know, this is the perfect solution.

查看更多
放我归山
3楼-- · 2019-01-04 01:33

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;
查看更多
家丑人穷心不美
4楼-- · 2019-01-04 01:39

Why not use window's own onload event ?

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

If I'm not mistaken, that is compatible across all browsers.

查看更多
Anthone
5楼-- · 2019-01-04 01:41

There are several different methods you have to use for different browsers. Libraries like jQuery give you a cross-browser interface that handles it all for you, though.

查看更多
何必那么认真
6楼-- · 2019-01-04 01:42

Cross browser window.load event

function load(){}

window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )
查看更多
干净又极端
7楼-- · 2019-01-04 01:48

document.body.onload is a cross-browser, but a legacy mechanism that only allows a single callback (you cannot assign multiple functions to it).

The closest "standard" alternative, addEventListener is not supported by Internet Explorer (it uses attachEvent), so you will likely want to use a library (jQuery, MooTools, prototype.js, etc.) to abstract the cross-browser ugliness for you.

查看更多
登录 后发表回答