JavaScript - Preload Images

风流意气都作罢 提交于 2019-12-06 08:27:25

问题


I'm working on a photo gallery, and I would like the ability to have a gif preloader show before the main image is loaded, and then show the main image.

So, this is what I got:

I have a #photo_place which is the div that holds the main photo. This changes depending on what thumbnail the user selects. When the user does select a thumbnail, this function is triggered:

function gallery(icon){

    $('#photo_place').css('background-image','url("../images/'+icon+'.png")');

}

Now, what I want, is to first, show a preloader gif at the #photo_place, load in the selected image ... somewhere, and when that image is loaded, replace the preloader, with the main image.

So maybe something like this?

function gallery(icon){
    $('#photo_place').css('background-image','url("../images/preloader.gif")');
    load.in.image'images/'+icon+'.png';

    if(load.in.image == true){
        $('#photo_place').css('background-image','url("loaded image")');
    }
}

Of course, that wasn't real JS, but something like that should work right?

Any ideas?

Thanks


回答1:


Perhaps you're looking for something like this?

function gallery(icon) {
   var preLoader = '../images/preloader.gif';
   var imagePath = '../images/' + icon + '.png';

   $('#photo_place').css('background-image','url("../images/preloader.gif")');

   var image = new Image();

   image.onload = function() {
      $('#photo_place').css('background-image', imagePath);
   }
   image.src = imagePath;
}

Also checkout Image class reference: http://www.javascriptkit.com/jsref/image.shtml



来源:https://stackoverflow.com/questions/10464970/javascript-preload-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!