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).
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.
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.
Answer: Use the DOMContentLoaded Eventready() equivalent without jQuery.
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>
This may help: http://www.freelancephp.net/en/domready-javascript-object-cross-browser/
Non jquery implementation of DOM ready
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With