How can I hide a page contents until all the images are fully loaded?

后端 未结 5 1853
谎友^
谎友^ 2021-01-14 01:09

I am trying to optimize a site which loads terribly. I already reordered, compressed and minified js and css, but the biggest problem are the images. This site has some real

5条回答
  •  逝去的感伤
    2021-01-14 01:31

    I've written my own js image preloader before, what I'm about to post is pseudo-similar to it but will need some work. Basically in order to make your page load nicely, the answer isn't to hide the body to stop it jumping around, rather beautify what happens when the images do load. Besides throwing out the baby with the bath water, generally sites appear to the user to load faster if they can see something happening while they wait.

    So what you need to do (for each image, or atleast each major or large image) is display a loading gif (check out http://ajaxload.info) while the image loads, then when it is finished you can use jQuery to animate it's container to the correct height and fade in the image. This stops your page jumping around (or rather makes it look prettier while it jumps).

    To acheive this effect, something like this should do the trick:

    function imageLoader(elem)
    {
      //set all images in this elem to opacity 0
      elem.children('img').css('opacity', '0');
      var image = new Image();
      //show loading image
      elem.append('html for loading image');
    
      //when the image loads, animate the height of the elem and fade in image
      image.onload=function()
      { 
           var h = image.height;
           elem.animate({height:h+'px'}, function(){
             elem.children('img').fadeIn();
             elem.children('html for loading image').remove(); 
           });
      };
    
      image.src=elem.children('img').attr('src');
    }
    

    Use it like this:

    imageLoader($('someElementWithAnImageTagInside'));
    

    Again this is just psuedocode really but hopefully should give you some ideas.

    Hope this helps

提交回复
热议问题