4

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 someone 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.

Community
  • 1
  • 1
buley
  • 24,595
  • 17
  • 76
  • 99

2 Answers2

6

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

Community
  • 1
  • 1
Lasse Espeholt
  • 17,092
  • 5
  • 57
  • 97
  • 1
    The above breaks when using Mixpanel; you need to include an event parameter. See: https://github.com/jenkinsci/jenkins/commit/5227403 – Jesse Glick Mar 12 '13 at 18:43
1

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

NoBugs
  • 8,418
  • 10
  • 72
  • 132