1

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.

Ben
  • 257
  • 1
  • 15
  • 1
    *"only after the page as been fully loaded"* What do you mean by that? The **HTML** of your page will either be fully-loaded or actively loading already. What do you want to be in the queue before the images? Scripts? – T.J. Crowder May 23 '16 at 11:40
  • i meant when the whole page has finished loading. just like the $(window).bind("load", function() {... works. only i need a function which will work for all elements and not only specific elements i manually write. – Ben May 23 '16 at 11:47

1 Answers1

4

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

Dan
  • 5,836
  • 22
  • 86
  • 140
  • Great Idea! Thanks. actually i was just starting to test this exact idea :) – Ben May 23 '16 at 12:04
  • Will it actually make the page load faster? – Ben May 23 '16 at 12:18
  • 1
    Ultimately you're still loading everything so the total page size + resources will be the same (a few bytes larger because of the new JS code). All it's doing is deferring the load of the bg images until all else has loaded. CSS bg images don't block page rendering so it would depend on your use-case as to whether it offered any perceived benefit to the user to defer their loading. If you're hitting maximum concurrent request limits (http://stackoverflow.com/questions/985431/max-parallel-http-connections-in-a-browser) then it could be of benefit to defer but technically there's little benefit. – Dan May 23 '16 at 13:01
  • Thanks! that's very helping! – Ben May 23 '16 at 16:59