EN
JavaScript - on resources ready
6
points
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: