addLoadEvent is not helping with onload conflict

血红的双手。 提交于 2019-12-06 01:07:13

Your code is fine. The problem is that setting event handlers in the DOM 0 way doesn't ensure that they won't replaced by other code.

You may try the new W3C standard addEventListener and the IE version attachEvent, because the handlers you attach by them cannot be replaced by 3rd party code.

// window.onload W3C cross-browser with a fallback
function addLoadEvent(func) {
  if (window.addEventListener)
    window.addEventListener("load", func, false);
  else if (window.attachEvent)
    window.attachEvent("onload", func);
  else { // fallback
    var old = window.onload;
    window.onload = function() {
      if (old) old();
      func();
    };
  }
}

Note, that IE will execute the function in reversed order not in the order you added them (if this is a concern).

Finally, I don't know when you want to run your code, but if you don't want to wait for images to load you can execute your functions earlier then window.onload.

Dean Edwards has a nice script which will let you to do that.

With this you can attach your functions for an earlier event: document.ready (DOMContentLoaded)

// document.ready
function addLoadEvent(func) {
  if (typeof func == "function") {
    addLoadEvent.queue.push(func);
  }
}
addLoadEvent.queue = [];

//////////////////////////////////////////////////////////////////////////////

// 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: execute the queue
  var que = addLoadEvent.queue;
  var len = que.length;
  for(var i = 0; i < len; i++) {
    if (typeof que[i] == "function") {
      que[i]();
    }
  }
};

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

Note: the usage is the same for both methods as it was for your version.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!