JavaScript - on resources ready

6 points
Created by:

In this article we would like to show how to write in pure JavaScript own function that executes some logic when DOM and resources loaded as sync part of a web page are ready.

The solution in below example is similat to jQuery $(document).ready(...) function with additional waiting when all images, styles, JavaScript files, fonts, etc. are ready - resources loaded in sync mode.

Note: below script is executed after sync resources are loaded, so copy it to local html file and test.

Quick solution:

// ONLINE-RUNNER:browser;

<!doctype html>
  <img src="" />

    function handleResourcesReady(callback) {
        if (document.readyState === 'complete') {
        } else {
          	if (callback.$$__PROXY__$$) {
            var proxy = callback.$$__PROXY__$$ = function(e) {
                if (document.readyState === 'complete') {
            document.addEventListener('readystatechange', proxy);

    function cancelResourcesReady(callback) {
        var proxy = callback.$$__PROXY__$$;
        if (proxy && delete callback.$$__PROXY__$$) {
            document.removeEventListener('readystatechange', proxy);

    // Usage example:

    handleResourcesReady(function() {
        console.log('Resources are ready!');

To know more check below articles:

  1. JavaScript - load events order for window, document, dom, body and elements
  2. JavaScript - document ready equivalent without jQuery
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂