zoukankan      html  css  js  c++  java
  • 图片的预加载(待续)

    1.预加载的好处

       提高打开页面的速度,提高用户的体验。

    2.缺点

      增加了无用的请求。

    3.实现  

    function  preLoad(url,fn){
          var img = new Image();
        img.src = url;
        if(img.complete){
          fn.call(img);
        }else{
          img.onload = function(){
            img.onload = null;
            fn.call(img);
          }
        }     }

    提高效率获取图片尺寸:参考

    var imgReady = (function(){
        var list = [],intervalId = null,
        tick = function(){
        for(var i=0;i<list.length;i++){
          list[i].end?list.splice(i--,1):list[i]();
        }
        !list.length&&stop();
      },
      stop = function(){
        clearInterval(intervalId);
        intervalId = null;
      
      };
      return function(url,ready,load,error){
        var onready,width,height,newWidth,newHeight,img = new Image();
        img.src = url;
        if(img.complete){
          ready.call(img);
          load&&load.call(img);
          return;
        }
        width = img.width;
        height = img.height;
        img.onerror = function(){
          error&&error.call(img);
          onready.end = true;
          img = img.onload = img.onerror = null;
        }
        onready = function(){
          newWidth = img.width;
          newHeight = img.height;
          if(newWidth !== width || newHeight !== height||newWIdth*newHeight >1024){
            ready.call(img);
            onready.end = true;
          }
        }
        onready();
        img.onload = function(){
          !onready.end && onready();
          load && load.call(img);
          img = img.onload = img.onerror = null;
        }
        if(!onready.end){
          list.push(onready);
          if(intervalId === null){
            intervalId = setInterval(tick,40);
          }
        }
      }
    })()

    参考文献:

    http://www.cnblogs.com/rt0d/archive/2011/04/17/2018646.html

    http://www.cssbox.net/js-img-onload.html

    http://www.qianduan.net/pure-css-image-preloader.html

    改进版:http://www.planeart.cn/?p=1121

  • 相关阅读:
    Sublime Text 3 Build 3143 可用License
    npm安装cnpm报错
    使用proxy来简单的实现一个观察者
    时间倒计时提醒
    JavaScript设计模式
    异步方法(promise版)出错自调用
    co模块源码学习笔记
    go new() 和 make() 的区别
    广度优先搜索算法
    并发和并行有什么区别?(转)
  • 原文地址:https://www.cnblogs.com/shamoguying1140/p/3024507.html
Copyright © 2011-2022 走看看