0

is this function that i wrote in jquery, will be a good way to preload? thank you

function loader(){

        imgTag('#check');

        function imgTag(whereToAppend){
            var image = 'image.jpg';

            $(whereToAppend).append('<img id="imgWrapper">');

            $('#imgWrapper').attr('src', image).hide().one('load',function(){
                $(this).fadeIn('slow');
            })
        }


    }
takeItEasy
  • 3,981
  • 2
  • 15
  • 10

1 Answers1

1

I would suggest using the following solution to preload images:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

Source: Preloading images with jQuery

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293
  • jQuery returns a collection, and you only need the first element. Hence you use `[0]` or `.get(0)` – Johan Apr 22 '12 at 18:18
  • so the img tag is hide until image is fully downloaded? – takeItEasy Apr 22 '12 at 18:21
  • You need to show the images manually. They are just preloaded here. So you get rid of the loading-effect of the images. Just add the images that youre planning to show in the array and show them as usual whenever you like – Johan Apr 22 '12 at 18:22
  • ok! thanks for our quick reply. but i'm still confused of preloading... – takeItEasy Apr 22 '12 at 18:25
  • as i understood the array of images will added on DOM but they are not showed on page still i call them. isn't it? – takeItEasy Apr 22 '12 at 18:28
  • They are preloaded but not appended to the DOM in this answer. However, there are answers in the thread that i linked to that has that kind of solutions as well. Just pick the one that suits you best – Johan Apr 22 '12 at 18:36