Liam
Liam

Reputation: 9855

Preload background images with jQuery?

I have a div thats currently set to display none, The Div has a background image that is approx 5000px wide, 2000px high.

I toggle the div display attirbute with jquery on a button click only with the image being so big the div loads and the image loads 1/2 seconds afterwards; is there a function where I can show a preloader until the image is ready and then display it?

Thanks

Upvotes: 3

Views: 20841

Answers (3)

JustinW
JustinW

Reputation: 271

This question was posted up a while back and answered just using vanilla javascript, but can be adapted to your scenario pretty easily.

Preloading CSS Images

$(document).ready( function() {

    var c = new Image();

    c.onload = function(){
        $("#Your Div ID").css("background-image", "url(Path to Background Image)");  
    }

    c.src = "Path to Background Image";

});

Upvotes: 5

YuS
YuS

Reputation: 2045

Try to use native javascript's Image object to preload the image.

Also consider about to avoid using such huge images on the web by making tiles for example.

Upvotes: 1

Related Questions