laurent
laurent

Reputation: 90776

A good cross-browser "ready" event without using jQuery?

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

Upvotes: 6

Views: 1520

Answers (3)

shawndumas
shawndumas

Reputation: 1413

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>

Upvotes: 3

Henry
Henry

Reputation: 2187

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

Non jquery implementation of DOM ready

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

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.

Upvotes: 0

Related Questions