Fire an event after preloading images

前端 未结 10 1916
北海茫月
北海茫月 2020-12-25 15:25

This is the code I use to preload images, I\'m not sure if it\'s the best one. My question is, how can I fire and event, for an example alert(); dialog after is has finished

10条回答
  •  失恋的感觉
    2020-12-25 15:46

    jquery preloading multiple images serially can be done with a callback.

    function preload_images(images_arr, f, id){
        id = typeof id !== 'undefined' ? id : 0;
        if (id == images_arr.length)
            return;
        $('').attr('src', images_arr[id]).load(function(){
            console.log(id);
            f(images_arr[id], id);
            preload_images(images_arr, f, id+1);
        });
    }
    

    For example:

    preload_images(["img1.jpg", "img2.jpg"], function(img_url, i){
        // i is the index of the img in the original array
        // can make some img.src = img_url
    });
    

提交回复
热议问题