Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS wait for CSS background image to load

It's easy to keep javascript waiting for some images to load if those are classic HTML images.

But I can't figure how to do the same if the image is loaded as a CSS backuground-image!

Is it possible?

The jQuery .load() method doesn't seem to apply.. and I'm short of ideas

like image 741
Valentino Avatar asked Jan 28 '12 03:01

Valentino


2 Answers

It looks for elements with src attribute or backgroundImage css property and calls an action function when theirs images loaded.

/**
 * Load and wait for loading images.
 */
function loadImages(images, action){
    var loaded_images = 0;
    var bad_tags = 0;        

    $(images).each(function() {
    //alert($(this).get(0).tagName+" "+$(this).attr("id")+" "+$(this).css("display"));
        var image = new Image();
        var src = $(this).attr("src");
        var backgroundImage = $(this).css("backgroundImage");            
        // Search for css background style
        if(src == undefined && backgroundImage != "none"){
            var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;                
            src = pattern.exec(backgroundImage)[1];                
        }else{
            bad_tags++;
        }
        // Load images
        $(image).load(function() {
            loaded_images++;                
            if(loaded_images == ($(images).length - bad_tags))
                action();
        })
        .attr("src", src);
    });
}
like image 132
Arkadiusz Cieśliński Avatar answered Sep 25 '22 11:09

Arkadiusz Cieśliński


One alternate approach would be to fetch the image data via AJAX as a base64 encoded png and apply it to the element's background-image property.

For example:

$.get('/getmyimage', function(data) {
    // data contains base64 encoded image
    // for ex: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==

    $('#yourElement').css('background-image', 'url("' + data + '")');
});

You will also need a server side script that reads the image, converts it into base64 encoded png (and cache it maybe) and return the same.

like image 29
techfoobar Avatar answered Sep 22 '22 11:09

techfoobar