Ask js how to judge the picture loading of css background url () is complete.
recently encountered a picture loading optimization problem, I want to set a background, but there is a certain time to load the picture, so I want to load the picture before the completion of a waiting icon, similar to loading, but do not know how to judge css background url (), if the picture img can directly use the onload method, how should I do better?
or how should I cache an image of about 2m? Thank you for your advice.
var loading = true;
var img = document.createElement('img');
img.src = 'url';
img.onload = function(){ loading = false; }
in fact, I already know that chrome caching is actually quite good. Of course, opening developer mode is actually disable cache, so I would like to remind the debugger to pay attention to this.
do I have to use background? In fact, you can use the loading diagram as background, and the 2m picture can be used with img
<img class="bg-img test-img" src="2M"/>
.bg-img {
background url(loading)
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
.test-img {
width 200px
height 200px
}
first of all, there is no event of javascript to judge the loading state of background image. At present, the best solution to this problem is to new an Image, set the src to the path of the image as background image, and then listen for the load event of the image.
refer to codepen
for specific implementation.
if you want to use off-the-shelf, someone packaged a jquery plug-in: waitForImages , using the same method as above.
has been tested, and this scheme is feasible even if the browser turns off the cache.