Ready() for the new era

Back in the day when jQuery ruled the roost, we would use the ready handler to make sure our code ran after the DOM and stylesheets had completely loaded.


$( document ).ready(function() {
  // Handler for .ready() called.
});

(Or, more likely, the recommended version.)


$(function() {
  // Handler for .ready() called.
});

But of course we don’t rely on loading jQuery in our head anymore. But nobody wants to write out the full logic manually.


if (document.readyState != "loading") {
  bootstrap();
} else {
  document.addEventListener("DOMContentLoaded", bootstrap, false);
}

But if we’re loading our code asynchronously, we kind of have to. Some people went as far as to synchronously load their JavaScript right before the </body> tag. That will make sure everything is ready when it runs, but at the cost of loading all your JavaScript later.

But there is a nice, short boilerplate that you can use that makes it easy to trigger on ready:


const ready = new Promise((resolve, _) => {
    if (document.readyState !== 'loading') resolve();
    else document.addEventListener('DOMContentLoaded', resolve);
});

Slap that basically anywhere and you can then run ready.then( ... ) anywhere in your code base that you can see it. And you don’t need to be careful about making sure there’s only one declaration. (Unless you have dependencies on initialization order.) A short handful of lines to give you a more fluent syntax for scheduling things on ready.

And unlike the old jQuery version, you don’t need to load it synchronously before everything else.


Leave a Reply