0

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.

simon
  • 12,666
  • 26
  • 78
  • 113
saunders
  • 969
  • 4
  • 14
  • 25
  • one question... you are loading the bg through css so that it loads even when js is disabled but then what about the content? you don't care about that? :) – Atul Dravid Apr 22 '11 at 11:02
  • i have a special no js file with html5. so if no js is detected i have display: block on the content – saunders Apr 22 '11 at 11:08

2 Answers2

2

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.

Tom Gruner
  • 9,635
  • 1
  • 20
  • 26
  • ahh so you fake the browser to load that image but by the time that invisible image is loaded my background image would have loaded and it wont do any flicker? – saunders Apr 22 '11 at 11:19
  • yeah, that is exactly it. If you search for image preloading too, that is another strategy you could use. – Tom Gruner Apr 22 '11 at 15:20
  • ah wicked. thanks for that and thanks for the other idea. im going to give your tip a go first:) – saunders Apr 22 '11 at 15:47
  • 1
    What about if you need to strictly use a background (because of its positioning properties; with the image I'd have to code it myself with jquery)? There should be a way to check if a source finished the download. – wonderwhy Aug 13 '14 at 13:37
  • That looks tempting to use but unfortunately this function is inconsistent across browsers when used on images: http://api.jquery.com/load-event/ – Oriol Dec 07 '15 at 22:55
0

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?

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247