0

I have a div with an inline background style. I want to prevent this background image from loading as long as JS is enabled, to use less data, but let it load if JS is disabled. I also want to be able to get the URL of the image later on using jQuery.

I currently have this in a <script> element in my <head>, so that it works as quickly as possible (adapted from this answer on SO):

JS

function removeBackgroundImagesBeforeTheyLoad() {
      var divs = document.getElementsByTagName("div");
      for (var i = 0; i < divs.length; i++) {
          divs[i].style.removeProperty("background");
      }
}
// Fire the function every microsecond
var timer = setInterval(function() {
     removeBackgroundImagesBeforeTheyLoad();
}, 1);
// Stop firing the function after 3 secs
setTimeout(function() {
    clearInterval(timer);
}, 3000);

This hides the image, but still allows it to load.

Community
  • 1
  • 1
binaryfunt
  • 6,401
  • 5
  • 37
  • 59
  • 1
    use CSS `div{background-image: none !important;}`. to tie to js, disable the stylesheet and un-disable it via JS. – dandavis Sep 22 '15 at 17:11
  • `setInterval` looks **dangerous** to me.. – Rayon Sep 22 '15 at 17:22
  • @dandavis Could you do it without having an extra HTTP request for the extra stylesheet? – binaryfunt Sep 22 '15 at 17:43
  • you could use a – dandavis Sep 22 '15 at 19:24
  • @dandavis Good idea, but unfortunately, when JS is disabled, the `disabled` attribute doesn't seem to work – binaryfunt Sep 23 '15 at 17:41
  • @BinaryFunt: yeah, its in the spec but i wasn't 100% sure it's followed. there's 5 other ways though. here's one: change my css above to `html.js div{backgr...` and then in script: `document.documentElement.className+=" js";` – dandavis Sep 23 '15 at 17:46
  • @dandavis I found another way though: `var style = document.getElementsByTagName("style")[0];` then `style.innerHTML = "div { background-image: none !important; }";` **Update** Oh, just saw your comment – binaryfunt Sep 23 '15 at 17:48
  • @BinaryFunt: that's another. anything will be better than iterating the DOM and modding many element styles... – dandavis Sep 23 '15 at 17:50

1 Answers1

0

use background=none

function removeBackgroundImagesBeforeTheyLoad() {
  var divs = document.getElementsByTagName("div");
  for (var i = 0; i < divs.length; i++) {
      divs[i].style.background=none;
  }
}
Sandeep
  • 1,461
  • 13
  • 26