0

I have a placeholder background image that i want to replace after its loaded.

$.get("BIG-IMAGE-URL").done(function(data){
    $('.MY-DIV-CLASS').css('background-image', 'url("BIG-IMAGE-URL")');
});

Does anyone know how to make a simple function like this?

  • JS seems overkill for this as you can just use CSS/HTML and save having to write and make another AJAX call for every required image: https://stackoverflow.com/questions/14748750/placeholder-background-image-while-waiting-for-full-image-to-load – Rory McCrossan Oct 03 '17 at 08:49
  • Are you trying to only load the image if it's available? If so this may be helpful: https://stackoverflow.com/questions/4285042/asynchronously-load-images-with-jquery – Nick Cordova Oct 03 '17 at 08:49

1 Answers1

0

You can load your big image with javascript, and set the CSS background in the load event handler.

var img = new Image();   // Create new img element
img.addEventListener('load', function() {
  // set background here
  $('.MY-DIV-CLASS').css('background-image', 'url("bigImage.png")');
}, false);
img.src = 'bigImage.png'; // Set source path

Source: MDN Using_images

Additionally, here is a similar solution using jQuery How can I check if a background image is loaded?

julian soro
  • 4,868
  • 5
  • 28
  • 36