1

How can you cancel the loading of an image defined by a background-image attribute?

There a few questions that show how to cancel the loading of an <img> tag by setting the src to '' or to a different image (such as this one, answered by Luca Fagioli). But this does not work for background images.

Luca provided a jsfiddle ( jsfiddle.net/nw34gLgt/ ) to demonstrate the <img src="" /> approach to canceling an image load.

But modifying that jsfiddle to use background-image instead clearly shows that the image continues loading, even if:

you do background-image: none (as suggested here)

or background-image: url("web.site/other_image.jpg")

or background-image: url('').

In fact, in my testing on Firefox 54, the background image continues loading even if you do window.stop() or close the tab.

So, is there any way at all to stop loading a background image once it starts?


My use-case for this is client-side, so I can't change the site to not use background images. I am viewing a gallery of many thumbnail images, but the thumbnails are much larger than they need to be. Smaller versions are available so I wanted to replace the large thumbnails with the smaller versions via Greasemonkey to ease the network load on my poor, slow connection. Each entry in the gallery is a <div> with a background-image inside an <a> linking to the full-size image. (using Fotorama).

Gibbous
  • 11
  • 1

1 Answers1

0

If you need to target inline styles on the elements, then I think you can run a script near the bottom of the page to do that.

Testing this locally, the original images do not show as loading in the network tab.

var allDivs = document.getElementsByTagName('DIV');

for (var i = 0; i < allDivs.length; i++) {
  // check for inline style
  var inlineStyle = allDivs[i].getAttribute('style');

  // check if background-image is applied inline
  if (inlineStyle && inlineStyle.indexOf('background-image') != 1 ) {
    allDivs[i].style.backgroundImage = 'url("newImg.jpg")'; // assign new value?
  }
}

That is going to grab every div, so hopefully these elements have a class you can use to query first. Then you have a smaller collection to run the above on.

Classes, not inline styles:

If you could target classes, it would look a bit cleaner. You could create a new class and use it.

var els = document.querySelectorAll('.bg-img');
for (var i = 0; i < els.length; i++) {
  els[i].classList.remove('bg-img');
  els[i].classList.add('no-bg-img');
}
Brian Wagner
  • 371
  • 2
  • 7
  • This does not work when I test it. The original bg image continues loading despite being replaced. The network readout doesn't show the loading of any bg images until they're complete, it seems, so it's misleading. Using WIndows' resource monitor or my router's bandwidth monitor shows the original background image is still downloading. – Gibbous Jul 22 '17 at 09:18