JoSch
JoSch

Reputation: 990

Deferred (lazy) loading of background images?

I'm using a simple script to cause a deferred loading of all images on a page; the path for the image sources is contained in a data-src attribute and then put into the actual srcattribute of the img tag(s). Pretty much how most (?) implementations of the lazy loading method work.

Here's the script:

[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
  img.setAttribute('src', img.getAttribute('data-src'));
  img.onload = function() {
    img.removeAttribute('data-src');
  };
});

I would like to use the same script for deferred loading of background images as well. How do I have to change it so that the data-src attribute ends up in the url-value of a div's background-image-property?

I tried the following with no results, because the script doesn't recognise background-image as a property:

[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
  div.setAttribute('background-image', div.getAttribute('data-src'));
  div.onload = function() {
    div.removeAttribute('data-src');
  };
});

Upvotes: 0

Views: 2056

Answers (2)

CognitiveDesire
CognitiveDesire

Reputation: 784

[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
  div.style.backgroundImage="url('" + div.getAttribute('data-src') + "')";
  div.onload = function() {
    div.removeAttribute('data-src');
  };
});

Try this

Upvotes: 0

James
James

Reputation: 211

Problem may be with the background image as an attribute. Have you tried setting the style with the background image?

[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
  div.setAttribute("style","background-image: url(" + div.getAttribute('data-src') + ");");
  div.onload = function() {
    div.removeAttribute('data-src');
  };
});

Upvotes: 3

Related Questions