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.