Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 591
laurent Avatar asked Aug 11 '11 13:08

laurent


People also ask

How can I implement my own $( document .ready functionality without using jQuery?

There are three options: If script is the last tag of the body, the DOM would be ready before script tag executes. When the DOM is ready, "readyState" will change to "complete" Put everything under 'DOMContentLoaded' event listener.

Is jQuery cross browser compatible?

Cross-browser compatibility — jQuery supports older browsers which do not do well with modern tools, frameworks or libraries. jQuery-powered applications work well on all browsers.

Which one is equivalent to $( document .ready function?

Answer: Use the DOMContentLoaded Eventready() equivalent without jQuery.


2 Answers

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>
like image 174
shawndumas Avatar answered Oct 20 '22 06:10

shawndumas


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

Non jquery implementation of DOM ready

like image 34
Henry Avatar answered Oct 20 '22 07:10

Henry