Languages
[Edit]
EN

JavaScript - on resources ready

6 points
Created by:
Paris-Bateman
504

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>
<html>
<body>
  <img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
  <script>

    function handleResourcesReady(callback) {
        if (document.readyState === 'complete') {
            setTimeout(callback);
        } else {
          	if (callback.$$__PROXY__$$) {
            	return;
            }
            var proxy = callback.$$__PROXY__$$ = function(e) {
                if (document.readyState === 'complete') {
                    cancelResourcesReady(callback);
                    callback();
                }
            };
            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!');
    });
    
  </script>
</body>
</html>

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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.

❤️💻 🙂

Join