Ben Ben - 1 year ago 42
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('');"></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', '')');

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?


Dan Dan

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="">Element with bg</div>
<div>Element without bg</div>
<div data-bg="">Element with bg</div>


    $(this).css('background','url(' + $(this).data('bg') + ')');

I knocked this up to demonstrate: