I have this code
$(document).on('readystatechange', function (){
debugger;
if (document.readyState === 'complete') {
$('img').each(function() {
console.log('image printed=" +this);
}
})
})
It runs properly when I hit my localhost page for the 1st time, but if I reload the same page (i.e. try to access the same page again) document.readyState changes almost with 1 second from interactive to complete (even though images are not loaded).
Not able to understand the issue, is it because of cache, if yes, how can I ensure that my above code runs only after all images have loaded (whether they are coming from browser cache or from backend)
Image tag is like this: /abc.jpg" width="45" height="45">
If you are looking for logic to be executed after the paint job has finished, i.e. the loading of your images, then you are looking for the window.onload method as opposed to the document.ready method.
Why is that? There is a significant difference between the two. The document.ready method executes as soon as the DOM Nodes are available, as opposed to an actual graphical presentation being represented to the the user. The window.onload method waits for the browsers paint job to be complete, meaning that all graphical presentations are available for the user.
You will see this effect in form of alerts in my example below. I even put the window.onload method first so that you can see that it's not due to the order in which they are declared.
window.onload = function() {
alert('I fire after images have loaded');
}
$(document).ready(function() {
alert('I fire before images are loaded');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=QEzyEzU6nVn4d_vdALhsT9UAtTUEVhwrT-kM5ogBqKM" />
<img src="https://i.picsum.photos/id/430/200/200.jpg?hmac=RbYQ27bVLRKt5ScfTYiQ_ePoVdo70X4eWg2KPc6JF0I" />
<img src="https://i.picsum.photos/id/998/200/200.jpg?hmac=Vc80YaPx9n6ZScRmWn3BK9EpGBVjYYCDlXpsZfYCOPw" />
<img src="https://i.picsum.photos/id/432/200/200.jpg?hmac=b4-kxXh_oTpvCBH9hueJurvHDdhy0eYNNba-mO9Q8bU" />