6

I need to create the equivalent of jQuery's ready event without using jQuery. It needs to work on as many browsers as possible and cannot mess up the body.onload handler (i.e. if there's already a handler set, the function shouldn't overwrite it). I checked jQuery's code but don't understand how it works because it uses many jQuery's functions.

Any suggestion on how to do that?

Edit: I have no control over where my code is going to be inserted that's why it needs to play as nicely as possible with the existing body.onload handler. It also means I cannot be sure the code will be inserted at the bottom of the page (most likely it won't be).

Charles
  • 48,924
  • 13
  • 96
  • 136
laurent
  • 79,308
  • 64
  • 256
  • 389
  • I recommend trying to understand how jQuerys works, or checking out another frameworks implementations such as mootools. – Loktar Aug 11 '11 at 13:26
  • 1
    possible duplicate of [javascript:how to write $(document).ready like event without jquery](http://stackoverflow.com/questions/3989095/javascripthow-to-write-document-ready-like-event-without-jquery) – Piskvor left the building Aug 11 '11 at 13:29

3 Answers3

3

Smallest cross browser DOMReady code, ever.

<html>
  <head>
    <script>
      var ready = function (f) {
        (/in/.test(document.readyState)) ?
          setTimeout('r(' + f + ')', 9) :
          f();
      };
    </script>
  </head>
  <body>
    <script>
      ready(function () {
        alert('DOM Ready!');
      });
    </script>
  </body>
</html>
shawndumas
  • 1,319
  • 13
  • 17
1

This may help: http://www.freelancephp.net/en/domready-javascript-object-cross-browser/

Non jquery implementation of DOM ready

Henry
  • 2,187
  • 1
  • 15
  • 27
0

Simply include your <script> tag at the very bottom. This way, it will only load after all the rest of the content had finished loading.

Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292