Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload background images with jQuery?

Tags:

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

like image 885
Liam Avatar asked Dec 04 '25 02:12

Liam


2 Answers

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";

});
like image 92
JustinW Avatar answered Dec 05 '25 18:12

JustinW


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.

like image 36
YuS Avatar answered Dec 05 '25 18:12

YuS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!