Skip to content Skip to sidebar Skip to footer

How To Defer Background Images Without Jquery Or Lazy Loading

Based on Patrick Sexton tutorial, I would like to defer background images in the same way I do here with img:

and how we set the value (here instead of setting the src attribute, we need to set the style attribute).

EDIT: I would even avoid the attribute check (in the JavaScript) here since our selector would do it.

Mark-up (Edit code here: http://codepen.io/anon/pen/rryxoK)

functioninit() {
  var imgDefer = document.querySelectorAll('div[data-src]');
  var style = "background-image: url({url})";
  for (var i = 0; i < imgDefer.length; i++) {

    imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));

  }
}

window.onload = init;
.deferImage {
  width: 800px;
  height: 600px;
}
<divclass="deferImage"data-src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Domestic-crested-duck-CamdenME.jpg/800px-Domestic-crested-duck-CamdenME.jpg"></div>

EDIT:To select by class name

Solution 2:

You can just do the same idea but instead of source you change the background in the init function

<divid='my-div'style=""data-src="your-image-here"></div><script>functioninit() {
var backgroundDefer = document.getElementById('my-div');
    if(backgroundDefer.getAttribute('data-src')) {
        backgroundDefer.style.background="url("+backgroundDefer.getAttribute('data-src')+")";
    }
}
window.onload = init;
</script>

Solution 3:

If all You want to do is set background after page load in pure JS use:

window.onload="myFunction()";

Where myFunction do the loading.

Solution 4:

I tried to use getElementsByClassName() and also ended up getting the backgroundDefer.getAttribute is not a function error. So I ended up inject id attribute, as well as the data-src attribute to be used as a placeholder for image URI and used the above code to defer background image.

I also have to first of all make an empty string in the background URI image.

<divid="my-div"class="parallax-background"data-stellar-background-ratio="0.7"data-src="https://d5y2y5rl4e57i.cloudfront.net/GWL_atl-108.jpg"style="background-image:url('')"></div><script>functioninit() {
  var backgroundDefer = document.getElementById('my-div');

  //have to use document.getElementById in order to use getAttribute() functionif(backgroundDefer.getAttribute('data-src')) {
        backgroundDefer.style="background-image:url("+backgroundDefer.getAttribute('data-src')+")";
  }
}
window.onload = init;

</script>

Post a Comment for "How To Defer Background Images Without Jquery Or Lazy Loading"