Loading image before switching background div in jquery

I have a webpage where I want to switch the background image of a div in response to user interaction. What I still have:

function updateImg() { 
   imgurl=buildImgURL(); // constructs a URL based on various form values
   $('#mainImage').css("background-image", "url("+imgurl+")");
}

This works exactly the same as I want, except for one. Due to the combination of relatively large background images and a relatively slow server (none of which can be easily fixed), it takes some time to load the image. Therefore, when the updateImg () function is called a div, it runs for half a second or so before a new background image is loaded. I want the old background image to remain until the new image finishes loading, and then instantly switches. Can this be done?

The background image is generated on the fly by the server, so any caching or preloading on the client side is not possible.

+3
source share
3 answers

How to set an image to an empty element?

$("<img id='loaderImg' src='"+imgUrl+"' onload='setBg(this.src)'/>");

Then when the image is uploaded

function setBg(imgUrl) {
    $("#mainImage").css("background-image", "url("+imgUrl+")");
    $("#loaderImg").remove();
}

That way, the image will be loaded into an image that will never be displayed, and set the background when the image is fully loaded (and also cached).

Not tested this, but I think it should work.

+3
source

You can define a CSS class with the background-image property set for the image, and then set the class of this div in your updateImg () function instead of directly changing the property. This can alleviate the problem.

Sort of:

function updateImg() { 
  imgurl=buildImgURL(); // constructs a URL based on various form values
  $('#mainImage').addClass('imageClassName');
}

CSS:

.imageClassName {
  background-image: url([url to image]);
}
0

, :

  • Preloading the image "loading .."
  • set the image "loading .." as the background of your div while your actual image is cooking
  • Once your actual image is available, do your stuff.

Please do not ask me to write jQuery. Its quite simple :)

Greetings

JRH.

-1
source

Source: https://habr.com/ru/post/1711175/


All Articles