undefinedfix
Sign in

Ask JS how to judge whether the picture loading of CSS background URL () is completed

BLuFeNiX edited in Wed, 08 Jun 2022

Recently, I encountered an image loading optimization problem. I want to set a background, but it takes a certain amount of time to load the image. So I want to give a waiting icon before the image is loaded, which is similar to loading, but I don't know how to judge the CSS background URL (). If the image img can directly use the onload method, what should I do?

Or how to cache a 2m image? Thank you for your advice.

4 Replies
user618075
commented on Wed, 08 Jun 2022

First, no JavaScript event can judge the loading status of background image. At present, the best solution to this problem is to create a new image, set SRC to the path of the background image, and then listen to the load event of the image.

Refer to codepen for specific implementation

If you want to use a ready-made one, someone packaged a jQuery plug-in: waitforimages, using the same method as above.

After testing, even if the browser turns off the cache, this scheme is also feasible.

Dean
commented on Wed, 08 Jun 2022
var loading = true;
var img = document.createElement('img');
img.src = 'url';
img.onload = function(){ loading = false; }
Braj
commented on Wed, 08 Jun 2022

In fact, I personally know that chrome caching is very good. Of course, it's disabled cache to open the developer mode, so I want to remind the debuggers to pay attention to this.

togelmania
commented on Wed, 08 Jun 2022

Do you have to use background? In fact, you can use the loading diagram as the background, and img is OK for the 2m image

<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
}
lock This question has been locked and the reply function has been disabled.