Extremely Clean Way to Preload all Images

Are your images flickering since you aren’t preloading them? This is kinda annoying. There’s a simple solution. Read below.

If you want an extremely clean, DRY, unobtrusive way to preload all images which are defined in your CSS without having to re-specify those urls as arguments into another JavaScript function, check out A New & Improved jQuery Script to Automatically Preload images from CSS

Go there and download preloadCssImages.jQuery_v5.js. Here is how you call the function in JQuery, once the DOM has been loaded:

<script type="text/javascript">

$(function() {
	$.preloadCssImages();
});

</script>

When trying to use this in another Rails app, I ran into this problem:

> Uncaught ReferenceError: jQuery is not defined
(anonymous function)preloadCssImages.jQuery_v5.js:21

> application.js:2Uncaught ReferenceError: preloadCssImages is not defined
(anonymous function)application.js:2
c.b.extend.readyjquery.min.js:29
owneryahoo-profiling.min.js:24
c.u

and was able to resolve it by modifying line 21 of preloadCssImages.jQuery_v5.js to make the function declaration look like this instead:

preloadCssImages = function(settings){

instead of what it was originally:

;jQuery.preloadCssImages = function(settings){

and then I had to modify this:

$(function() {
    $.preloadCssImages();
});

to be this instead:

$(function() {
    preloadCssImages();
});

I verified it worked since I no longer saw the Javascript error I was seeing and also in the Rails’ Webrick log I was able to see that the images were now getting pre-loaded.

VN:F [1.9.22_1171]
Rating: 4.0/5 (5 votes cast)
VN:F [1.9.22_1171]
Rating: +3 (from 3 votes)
Extremely Clean Way to Preload all Images, 4.0 out of 5 based on 5 ratings
Facebook Twitter Email

Leave a Reply