开发者

Are there universal alternatives to window.onload without using frameworks?

开发者 https://www.devze.com 2023-03-11 19:19 出处:网络
In a previous question I learned of a bug in my JavaScript related to using appendChild on the BODY element before the DOMReady event was fired.

In a previous question I learned of a bug in my JavaScript related to using appendChild on the BODY element before the DOMReady event was fired.

I was able to resolve this by wrapping my code in a window.onload event. Reading up on this, I have learned that window.onload only supports a single listener, and I can't guarantee I am not clobbering so开发者_Go百科meone else's listener or that someone else's listener is not clobbering mine.

Looking at the source for $(document).ready(function(){});, I realize there is perhaps a lot that goes into the simplicity of that syntax.

Is there a universal way for me to wait for the DOMReady event without using jQuery or another JS library? While it seems like that would do the trick, I would prefer not to have any dependencies on a third party library in order for my code to work correctly.


You can do something like:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* more code to run on page load */
});

which wraps the existing onload in a new function with an additional function. This is taken from http://www.webreference.com/programming/javascript/onloads/

However, for doing it on document ready and not onload (different things, onload is when everything is downloaded where ready is when the document are loaded) look at this question: $(document).ready equivalent without jQuery


You can use:

document.onpageshow= new function() {
//(Code here)
}

You can also replace "onpageshow" with "onload" for better compatibility.

This may also be helpful: https://developer.mozilla.org/en/DOM/element.addEventListener

0

精彩评论

暂无评论...
验证码 换一张
取 消