Reputation: 1918
What is the best way to preload a background image on a div with a class using jQuery?
<div id="wrapper" class="first">
</div>
.first {background:url(/image.jpg) repeat-x top center}
Upvotes: 0
Views: 859
Reputation: 149
You may use a whole image instead of using a number of separate image files and may make use of the xpos and ypos parameters of CSS background-position functionality. In this case just one image file is loaded and for once. And let CSS and the classes handle the rest of the stuff. Here is an example;
/*this is the style*/
<style type="text/css">
.first {
background: url(.....) no-repeat 0px 0px;
}
.second {
background: url(.....) no-repeat -200px -200px;
}
</style>
<div id="wrapper" class="first"></div>
Upvotes: 0
Reputation: 103348
If you wish to pre-load without changing your HTML markup, you can do this using jQuery:
$(function(){
$('<img/>')[0].src = "/image.jpg";
});
Upvotes: 0
Reputation: 21086
Just pre-loaded them as regular images, either using the Image object or an IMG tag inside a hidden DIV. Then when you change the class of your working DIV to one that has a CSS background of one of your pre-loaded images it will pull it from the client cache.
.preload { display: none; }
...
<div>
<img src="a.png" class="preload" />
<img src="b.png" class="preload" />
</div>
Upvotes: 1