saunders
saunders

Reputation: 989

Is it possible to check whether a background image has been loaded using jQuery?

I am trying to find out whether it is possible to check if a background image has been loaded before fading in the content? The background image is set in the css so if the user doesnt have js turned on they are still able to view the site.

I have tried $(".quick-load").load(function () { $("#content").fadeIn(); });

I have also used .ready() but none have had any effect.

The exact problem i am having is that the image will flicker on some occasions.

Any ideas would be helpful, thanks.

Upvotes: 0

Views: 5283

Answers (2)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

You can "preload" images by using a hidden <img>.

$('<img/>').attr('src', 'http://picture.com/pic.png').load(function() {
    $("#content").css({"background-image":"http://picture.com/pic.png"
                 .fadeIn();
});

How can I check if a background image is loaded?

Upvotes: 0

Tom Gruner
Tom Gruner

Reputation: 9635

I think you should try a slightly different approach, which is to load the image first in a hidden image tag, then on the load event do your cool fading

<img src="background.png" alt="" id="background" 
style="visibility:hidden;position:absolute" />

Then do:

$('#background').load(function() {
   $("#content").fadeIn(); }
});

This will work because the browser caches the image on load and it will be available to use in the background. Just make sure that the source for your invisible image and your background image are identical.

Upvotes: 2

Related Questions