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.

Apr.02,2022

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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf2738-31576.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf2738-31576.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?