image preloading function in jquery

916 Views Asked by At

I'm using the following function to preload images in my site:

$.fn.preload = function() {
  this.each(function() {
    $('<img/>')[0].src = baseurl + '/assets/images/' + this;
  });
};

If I call it with more than one image everything works as expected:

$(['img01.jpg', 'img02.jpg', 'img03.jpg']).preload();

But if I call it with just one image, I get the following error:

TypeError: $(...).preload is not a function $(function() { $(['img01.jpg']).preload(); });

Any ideas about what I'm doing wrong?

Thanks in advance.

1

There are 1 best solutions below

0
On

Please check this jsFiddle out, I'm loading an image from a web page...

$(document).ready(function () {
    $.fn.preload = function () {
        this.each(function () {
            debugger;
            $('img')[0].src = this;
        });
    }
    $(['http://datastore04.rediff.com/h1500-w1500/thumb/69586A645B6D2A2E3131/pvwbsmbfdegzorwo.D.0.Holi-Wallpapers-Images.jpg']).preload();
});