0

i need a way to preload background images, either by vanilla JS or jQuery. I am using pure CSS3 bg gallery, which is an ordinary ul, and each li represents full bg image.

There are no img tags, each li uses css background-image property. I have four galleries, and each one is loaded by AJAX on request.

If someone could point to some example, or some script which would help me preload images for each gallery, so when the gallery is loaded, the images are already preloaded.

You can see the test site at http://www.madebym.net/test/index.html

Only the first set of links is working, and each one points to new gallery.

fluxus
  • 559
  • 5
  • 15
  • 29

1 Answers1

1

I have a global utility function that I use to handle any image preloads (you can pass an Array of images to it).

    $.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            $('<img>').attr('src', arguments[i]);
            // For testing purposes: 
            //console.log('\n\u2713 Successfully Preloaded Image :: ');
            //console.log($('<img>').attr('src', arguments[i]));
        }
    }

Useage would be:

    $.preloadImages('test.jpg', 'test2.jpg'); // put all your images in there

But basically you are just creating a blank $('img'). Hope that helps!

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
  • Thanks, but i am not using any img tags. I need a way to preload li element which uses css background-image property. – fluxus Aug 30 '12 at 19:16
  • These images aren't placed on the page, but the image will be preloaded into your *cache*, so once you put them in the `
  • ` elements, they will appear instantly
  • – Mark Pieszak - Trilon.io Aug 30 '12 at 19:17
  • Not sure if i got you right...images will not appear on the page, but since they are cached they will be used by background-size property? – fluxus Aug 30 '12 at 19:22
  • Oh no, I just meant they are cached, you can now load them set them as the li background-image etc without worrying about them loading – Mark Pieszak - Trilon.io Aug 30 '12 at 19:30
  • Great! Just one more thing, do i need some preloader image with this or my AJAX call will wait for images to be preloaded? – fluxus Aug 30 '12 at 19:36
  • No you don't need anything, this is just designed to load up those images so when the ajax call is made it will be instant (since the huge images will be loaded already) :) – Mark Pieszak - Trilon.io Aug 30 '12 at 19:42
  • Ok, last thing:) Do i put this on main page, or on each page that is called by ajax? – fluxus Aug 30 '12 at 19:44
  • 1
    I'd probably put this in some file that's on all the pages, then put your array of images inside it, boom. – Mark Pieszak - Trilon.io Aug 30 '12 at 19:46