BBaysinger
BBaysinger

Reputation: 6987

How to detect if an `img` element load has started and/or a request has been made to the server

Is there an easy/efficient way to detect if an img element load has started and/or a request has been made to the server?

I swear I remember seeing (the first part of) this before on SO, but can't find it now.

I think I remember that the naturalWidth and naturalHeight properties are present if the image has started loading, but IDK if that is always true.

I am working with lazy loading, and would like to be able to prevent a request if one has not already been made. I more or less need to know as much as possible on this topic.

Specifically, in this particular case, the only place I can put JS is after the body, and we're not sure yet if converting every image to use data-src instead of src from the server is an option, so that may mean having to comb back through the DOM to figure out where everything is at, and try to cancel as much as possible without stopping anything that is already in progress, because that would cause redundancy (even though it may help metrics in a very dirty way).

BTW, we are not using browser-native lazy loading, because I've found that is only useful for a specific use case. It's can't really be relied upon for prioritizing images above the fold, since it loads some lazy elements below the fold before the window.load event fires. Which makes no sense to me (why it can't start doing that after window.load.) And why there are no options on the feature. Also why loading:lazy can't be set in CSS.

Upvotes: 0

Views: 59

Answers (1)

Eriks Klotins
Eriks Klotins

Reputation: 4180

Here is an example of how to control image loading:

https://jsfiddle.net/xnp6hLr4/2/

Your best bet is to load images dynamically and keep track of their states (not loaded, loading, loaded)

var isLoaded = false;
$(document).ready(function(){

    $('#image').one().bind('load',(function(){alert('loading complete'); isLoaded=true;  }));

    $('#startButt').click(function(){

        if (isLoaded)
        {
            alert('Image already loaded');
        }
        else
        {
            alert('Loading start');
            $('#image').attr('src', 'https://cdn.pixabay.com/photo/2022/08/31/11/01/kangaroo-7423042_960_720.jpg');
        }   
     });
});

Upvotes: 1

Related Questions