Okay, this might just be a silly question, though I'm sure there are plenty of other people asking the same question from time to time. Me, I just want to make 100% sure about it either way. With jQuery we all know the wonderful

$('document').ready(function(){});

However, let's say I want to run a function that is written in standard JavaScript with no library backing it, and that I want to launch a function as soon as the page is ready to handle it. What's the proper way to approach this?

I know I can do:

window.onload="myFunction()";

...or I can use the body tag:

<body onload="myFunction()">

...or I can even try at the bottom of the page after everything, but the end body or html tag like:

<script type="text/javascript">
myFunction();
</script>

What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's $.ready()?

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

support for older browsers is nice, but with as fast as tech is moving forward and people seem to be catching up quicker these days its not 100% needed but a nice bonus if possible. Overall I am trying to figure what if any of these is the standard across browsers. Do they all work? Does it matter which I choose? If they all work what would be suggested as the best vs the rest?
– chrisMar 28 '12 at 0:00

@clexmond putting script at the bottom vs top is something I've always understood for a variety of reasons. I tend to place it at the bottom, external files or on the page itself. But last couple years I've been spoiled by jQuery and other libraires. However I am now on a crusade of sorts trying to get a better understanding of javascript by itself with no lib backing it. So despite knowing what I know of javascript this simple little thing throws me off a bit as I want to make sure any script I do follows a compliant cross browser methodology.
– chrisMar 28 '12 at 0:04

4

You could check out the source of jQuery to see how they implement the document ready function and work from there.
– joshuahealyMar 28 '12 at 0:04

@DanA. Nice. I think that sums the answer to this question up some. So JavaScript alone, there's no absolute way of easily finding a ready state, a means of sorts has to be created to support it across the various browsers. Thank you for finding that and clarifying it better for me.
– chrisMar 28 '12 at 0:10

10 Answers
10

The simplest thing to do in the absence of a framework that does all the cross-browser compatibility for you is to just put a call to your code at the end of the body. This is faster to execute than an onload handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.

If you really don't want to do it this way and you need cross browser compatibility and you don't want to wait for window.onload, then you probably should go look at how a framework like jQuery implements its $(document).ready() method. It's fairly involved depending upon the capabilities of the browser.

To give you a little idea what jQuery does (which will work wherever the script tag is placed).

If supported, it tries the standard:

document.addEventListener('DOMContentLoaded', fn, false);

with a fallback to:

window.addEventListener('load', fn, false )

or for older versions of IE, it uses:

document.attachEvent("onreadystatechange", fn);

with a fallback to:

window.attachEvent("onload", fn);

And, there are some work-arounds in the IE code path that I don't quite follow, but it looks like it has something to do with frames.

Here is a full substitute for jQuery's .ready() written in plain javascript:

(function(funcName, baseObj) {
// The public function name defaults to window.docReady
// but you can pass in your own object and own function name and those will be used
// if you want to put them in a different namespace
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
// This is the one public interface
// docReady(fn, context);
// the context argument is optional - if present, it will be passed
// as an argument to the callback
baseObj[funcName] = function(callback, context) {
if (typeof callback !== "function") {
throw new TypeError("callback for docReady(fn) must be a function");
}
// if ready has already fired, then just schedule the callback
// to fire asynchronously, but right away
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
if (document.readyState === "complete") {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("docReady", window);

// pass a function reference
docReady(fn);
// use an anonymous function
docReady(function() {
// code here
});
// pass a function reference and a context
// the context will be passed to the function as the first argument
docReady(fn, context);
// use an anonymous function with a context
docReady(function(context) {
// code here that can use the context argument that was passed to docReady
}, ctx);

This has been tested in:

IE6 and up
Firefox 3.6 and up
Chrome 14 and up
Safari 5.1 and up
Opera 11.6 and up
Multiple iOS devices
Multiple Android devices

Create an IIFE (immediately invoked function expression) so we can have non-public state variables.

Declare a public function docReady(fn, context)

When docReady(fn, context) is called, check if the ready handler has already fired. If so, just schedule the newly added callback to fire right after this thread of JS finishes with setTimeout(fn, 1).

If the ready handler has not already fired, then add this new callback to the list of callbacks to be called later.

Check if the document is already ready. If so, execute all ready handlers.

If we haven't installed event listeners yet to know when the document becomes ready, then install them now.

If document.addEventListener exists, then install event handlers using .addEventListener() for both "DOMContentLoaded" and "load" events. The "load" is a backup event for safety and should not be needed.

If document.addEventListener doesn't exist, then install event handlers using .attachEvent() for "onreadystatechange" and "onload" events.

In the onreadystatechange event, check to see if the document.readyState === "complete" and if so, call a function to fire all the ready handlers.

In all the other event handlers, call a function to fire all the ready handlers.

In the function to call all the ready handlers, check a state variable to see if we've already fired. If we have, do nothing. If we haven't yet been called, then loop through the array of ready functions and call each one in the order they were added. Set a flag to indicate these have all been called so they are never executed more than once.

Clear the function array so any closures they might be using can be freed.

Handlers registered with docReady() are guaranteed to be fired in the order they were registered.

If you call docReady(fn) after the document is already ready, the callback will be scheduled to execute as soon as the current thread of execution completes using setTimeout(fn, 1). This allows the calling code to always assume they are async callbacks that will be called later, even if later is as soon as the current thread of JS finishes and it preserves calling order.

Putting the page initialization code after the body content works everywhere even very old browsers. Because of the possibility of using document.write() in your javascript and the simplicity that it leads to in coding/implementation, all javascript that isn't explicitly marked as defer or async is loaded sequentially as it is encountered in the page and everything that is before it in the file has already executed or been parsed.
– jfriend00Mar 28 '12 at 0:59

1

Added a full implementation of a plain javascript function called docReady().
– jfriend00Mar 26 '14 at 5:05

2

All that the tail script needs to be is a call to the initialisation code, so can be a single call to say init(), where functions to be called when the DOM is ready are added to init.
– RobGJun 6 '14 at 6:24

4

@Ced - It calls setTimeout() so that registering a new callback always has the same asynchronous behavior whether the document is already loaded or whether the document is not yet loaded. This avoids some subtle timing bugs in the calling code. The callback will never be called until after the current thread of jS finishes executing. Promises do the same thing with installing a new .then() handler for the same reason.
– jfriend00May 11 '16 at 15:12

3

@NabiK.A.Z. - It's called an IIFE (immediately invoked function expression). It provides a private function scope so your symbols (variables and functions) inside that don't conflict with the global namespace and can't be mussed with by other code. It's a very common way of isolating or protecting code in Javascript. It serves the same purpose as just putting all the code in a function and then calling that function, but this way, no global function name symbol gets defined.
– jfriend00Jun 28 '18 at 22:05

The trick here, as explained by the original author, is that we are checking the document.readyState property. If it contains the string in (as in uninitialized and loading, the first two DOM ready states out of 5) we set a timeout and check again. Otherwise, we execute the passed function.

And here's the jsFiddle for the trick which works across all browsers.

If the latter is in a script tag at the very bottom of your webpage then it will occur after all the dom elements above it have been loaded.
– csga5000Nov 14 '15 at 6:48

3

TRUE , but OP question was "pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it"
– Tom StickelNov 15 '15 at 2:23

3

For me this should be the accepted answer. What a fabulously simple solution and I agree on the IIFE not being a correct solution. You sometimes don't have control over when you can inject your script which makes the prerequisite requirement of an IIFE being loaded last as useless if for you want to use jQuery functions before the library has been loaded into the page.
– JonathanMar 3 '16 at 13:47

I have just developed the following. It's a rather simplistic equivalent to jQuery or Dom ready without backwards compatibility. It probably needs further refinement. Tested in latest versions of Chrome, Firefox and IE (10/11) and should work in older browsers as commented on. I'll update if I find any issues.

It's written to handle async loading of JS but you might want to sync load this script first unless you're minifying. I've found it useful in development.

Modern browsers also support async loading of scripts which further enhances the experience. Support for async means multiple scripts can be downloaded simultaneously all while still rendering the page. Just watch out when depending on other scripts loaded asynchronously or use a minifier or something like browserify to handle dependencies.

You're correct. It explicitly says that when you click through on the link. That doesn't mean that it's not cross-browser, it tries to mitigate for some of the idiosyncrasies which IE9+ still has. I never claimed anything to the otherwise in my answer :)
– Lorcan O'NeillNov 25 '15 at 11:32

1

I tested this on IE8 and it worked, though their current one on the link is different and looks to only support IE9, odd...
– rogerdpackOct 28 '16 at 17:39

I said it is the "only reliable way", not the "only way". I said "only reliable way" because it was the only way to do it in Netscape 2.0.
– Kernel JamesDec 9 '16 at 5:58

2

According to your revision history, you actually said "is the only (one of the) reliable(s) way to support old and new browsers.". Such language is easily misconstrued to be interpreted as the only way. I ain't taking back what I said, sorry.
– JonathanDec 20 '16 at 20:16

@99Problems-Syntaxain'tone why would you have more than one event listener?
– Zak The HatOct 5 '16 at 9:45

1

There are lots of reasons for having more than one event listener, for example if you are loading multiple scripts they each may want to attach event listeners to onClick for example, one changing colour of something, another registering the event with google analytics etc...
– 99 Problems - Syntax ain't oneOct 5 '16 at 10:21

Oh I couldn't agree with you more. I am a big fan of jQuery use it in almost anything I do javascript related. However I'm just trying to learn JavaScript from the core so I can be even better with applications I develop including what I would do with jQuery backing it.
– chrisMar 28 '12 at 0:09

then you can use that or window.onload, but there isn't a good cross browser solution. Here is a reading on how jQuery does it if you're interested: docs.jquery.com/…
– maxhudMar 28 '12 at 0:13

It seems like you could get it to work in theory by adding onload events to images and to window which should include every element.
– maxhudMar 28 '12 at 0:15

@maxhud: Are you aware of any browser where onload actually doesn't work? Or where placing the script at the bottom of the page doesn't work?
– user1106925Mar 28 '12 at 0:28