Ben Ben - 6 months ago 16
Javascript Question

Is there a way to load inline css background images only after page load?

I have a lot of images on my page which load as a background image of a div like that:

<div style="background-image:url('http://www.example.com/someimg.jpg');"></div>


And for page load speed purposes i want to load all those image only after the page as been fully loaded.

Now i could just add that background image with some jQuery like that:

$(window).bind("load", function() {
$('div').css('background-image', 'http://www.example.com/someimg.jpg')');
});


But i have a lot of images and also i use some dynamic php to load those images (which users update regularly), so i need some other solution which will work for any background image on the site.

Any ideas?

Thanks.

Dan Dan
Answer

You could do this by loading your images into a data attribute, rather than into an inline style attribute. Then use jQuery to loop through all elements with that data attribute and use the value to populate the style.

e.g. HTML:

<div data-bg="https://images.unsplash.com/photo-1463123081488-789f998ac9c4?format=auto&auto=compress&dpr=1&crop=entropy&fit=crop&w=1199&h=799&q=80">Element with bg</div>
<div>Element without bg</div>
<div data-bg="https://images.unsplash.com/photo-1462774603919-1d8087e62cad?format=auto&auto=compress&dpr=1&crop=entropy&fit=crop&w=1199&h=799&q=80">Element with bg</div>

jQuery:

$(window).load(function(){ 
  $('[data-bg]').each(function(){
    $(this).css('background','url(' + $(this).data('bg') + ')');
  });
});

I knocked this up to demonstrate: http://codepen.io/anon/pen/jqgLja