Simple jQuery Preloader Plugin

After several searches for a pre-loading plugin for jQuery I came up short – they either did too much and had hundreds of options I didn’t want, or they were packaged with something else had a lot of code I didn’t need. The following plugin will allow you to pass in a selector (div, body, any other element) and pre-load all images within it, the plugin is very lightweight with only 17 lines from start to finish.

I’ve left the options code there in-case I decide to extend it with some features at a later date.

As always, you’ll need a version of jQuery on the page (as it is a jQuery Plugin)

The Plugin

(function($){
	 $.fn.extend({
		preload: function(options) {
			var defaults = { };
			var options = $.extend(defaults, options);
			return this.each(function() {
				var o = options;
				var obj = $(this);
				var imageArr = [];
				$('img', obj).each(function(index) {
					imageArr[i] = new Image();
					imageArr[i].src = $(this).attr('src');
				});
			});
		}
	 });
})(jQuery);

The above plugin is VERY simple – All it does is loop through the passed in selector looking for images, once it finds an image it’ll create an HTML Image Object and set the source so pre-load the image. Just save the above code to a file e.g. jquery.preloader.js and include it in your HTML page. Use it like the following:

Plug-in Usage

<script type="text/javascript"> 
 $(function() {
      $('.divtopreload').preload();
 });
</script> 

If you have any questions or want any-more information please feel free to comment below.

About Steve

Web Developer, IT enthusiast & PC Gamer.
This entry was posted in Javascript and tagged , , . Bookmark the permalink.

4 Responses to Simple jQuery Preloader Plugin

  1. Liligi says:

    How do you use this with multiple images?

    • Steve says:

      Hi Liligi

      Just put all of the images you want to preload inside a DIV tag and it’ll do them all. If you need it in multiple DIVs you can change the selector when calling the plugin.

      Thanks

  2. girl_appliq says:

    Thank you – excellent script just what i was looking for utilising the CSS philosophy of seperation of markup and formatting – most similar scripts make direct reference to the image names in the calling script (not good)

    Many thanks again.

  3. Brennan says:

    It would be great to have a callback once all images have fully preloaded.

Leave a Reply

Your email address will not be published. Required fields are marked *