Image with declared width and height renders square before load

后端 未结 6 2359
不思量自难忘°
不思量自难忘° 2021-02-13 11:15

I have images with declared widths and heights, e.g.:

\"bar\"

They are within

6条回答
  •  感动是毒
    2021-02-13 11:38

    You can achieve the desired effect with the following solution.

    HTML:

    bar  
                 ▲                ▲  
                 ║                ╚═══ The class will be used for the lazy loader below  
                 ║  
                 ╚═══ Use faulty gif here to hide it from showing before loaded
    

    Hint: If you want the placeholder rectangle to be visible and in one color, consider using a 1x1 px image for blank.gif. It will load very fast and will stretch nicely to your proportions, filling it with the color of your choosing.

    JavaScript:

    /* lazyload.js (c) Lorenzo Giuliani
     * MIT License (http://www.opensource.org/licenses/mit-license.html)
     *
     * expects a list of:  
     * ``
     */
    
    !function(window){
      var $q = function(q, res){
            if (document.querySelectorAll) {
              res = document.querySelectorAll(q);
            } else {
              var d=document
                , a=d.styleSheets[0] || d.createStyleSheet();
              a.addRule(q,'f:b');
              for(var l=d.all,b=0,c=[],f=l.length;b= 0
        && rect.left   >= 0
        && rect.top <= (window.innerHeight || document.documentElement.clientHeight)
        )
      }
    
        var images = new Array()
          , query = $q('img.lazy')
          , processScroll = function(){
              for (var i = 0; i < images.length; i++) {
                if (elementInViewport(images[i])) {
                  loadImage(images[i], function () {
                    images.splice(i, i);
                  });
                }
              };
            }
          ;
        // Array.prototype.slice.call is not callable under our lovely IE8 
        for (var i = 0; i < query.length; i++) {
          images.push(query[i]);
        };
    
        processScroll();
        addEventListener('scroll',processScroll);
    
    }(this);
    

    Sources: The Lazyload script can be found here.

提交回复
热议问题