zoukankan      html  css  js  c++  java
  • 图片预加载

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>图片预加载实例</title>
    <script type="text/javascript" src="jquery-1.8.2.js"></script>
    </head>
    
    <body>
        <!--<img src="http://test/test.jpg" />-->
        <input type="button" value="loadImage" onclick="loadImage('http://test/test.jpg',imgLoaded)"/>
        <div class="showImg"></div>
        
        <script type="text/javascript">
        function loadImage(url, callback) {
            var img = new Image();
            img.src = url;
            
            if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数
                callback.call(img);
                return; // 直接返回,不用再处理onload事件
            }
            
            img.onload = function() {//图片下载完毕时异步调用callback函数。
                callback.call(img);// 将callback函数this指针切换为img。
                img.onload = null;
            };
        }
        
        function imgLoaded() {
            console.log(this.src);
            $('.showImg').html('<img src="'+this.src+'" />');
        }
        </script>
    </body>
    </html>

    再谈javascript图片预加载技术

    比onload更快获取图片尺寸

    文章更新:2011-05-31
    lightbox类效果为了让图片居中显示而使用预加载,需要等待完全加载完毕才能显示,体验不佳(如filick相册的全屏效果)。javascript无法获取img文件头数据,真的是这样吗?本文通过一个巧妙的方法让javascript获取它。

    这是大部分人使用预加载获取图片大小的例子:

     1 var imgLoad = function (url, callback) {
     2     var img = new Image();
     3 
     4     img.src = url;
     5     if (img.complete) {
     6         callback(img.width, img.height);
     7     } else {
     8         img.onload = function () {
     9             callback(img.width, img.height);
    10             img.onload = null;
    11         };
    12     };
    13 
    14 };

    可以看到上面必须等待图片加载完毕才能获取尺寸,其速度不敢恭维,我们需要改进。

    web应用程序区别于桌面应用程序,响应速度才是最好的用户体验。如果想要速度与优雅兼得,那就必须提前获得图片尺寸,如何在图片没有加载完毕就能获取图片尺寸?

    十多年的上网经验告诉我:浏览器在加载图片的时候你会看到图片会先占用一块地然后才慢慢加载完毕,并且不需要预设width与height属性,因为浏览器能够获取图片的头部数据。基于此,只需要使用javascript定时侦测图片的尺寸状态便可得知图片尺寸就绪的状态。

    当然实际中会有一些兼容陷阱,如width与height检测各个浏览器的不一致,还有webkit new Image()建立的图片会受以处在加载进程中同url图片影响,经过反复测试后的最佳处理方式:

     1 // 更新:
     2 // 05.27: 1、保证回调执行顺序:error > ready > load;2、回调函数this指向img本身
     3 // 04-02: 1、增加图片完全加载后的回调 2、提高性能
     4 
     5 /**
     6  * 图片头数据加载就绪事件 - 更快获取图片尺寸
     7  * @version    2011.05.27
     8  * @author    TangBin
     9  * @see        http://www.planeart.cn/?p=1121
    10  * @param    {String}    图片路径
    11  * @param    {Function}    尺寸就绪
    12  * @param    {Function}    加载完毕 (可选)
    13  * @param    {Function}    加载错误 (可选)
    14  * @example imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
    15         alert('size ready: width=' + this.width + '; height=' + this.height);
    16     });
    17  */
    18 var imgReady = (function () {
    19     var list = [], intervalId = null,
    20 
    21     // 用来执行队列
    22     tick = function () {
    23         var i = 0;
    24         for (; i < list.length; i++) {
    25             list[i].end ? list.splice(i--, 1) : list[i]();
    26         };
    27         !list.length && stop();
    28     },
    29 
    30     // 停止所有定时器队列
    31     stop = function () {
    32         clearInterval(intervalId);
    33         intervalId = null;
    34     };
    35 
    36     return function (url, ready, load, error) {
    37         var onready, width, height, newWidth, newHeight,
    38             img = new Image();
    39         
    40         img.src = url;
    41 
    42         // 如果图片被缓存,则直接返回缓存数据
    43         if (img.complete) {
    44             ready.call(img);
    45             load && load.call(img);
    46             return;
    47         };
    48         
    49         width = img.width;
    50         height = img.height;
    51         
    52         // 加载错误后的事件
    53         img.onerror = function () {
    54             error && error.call(img);
    55             onready.end = true;
    56             img = img.onload = img.onerror = null;
    57         };
    58         
    59         // 图片尺寸就绪
    60         onready = function () {
    61             newWidth = img.width;
    62             newHeight = img.height;
    63             if (newWidth !== width || newHeight !== height ||
    64                 // 如果图片已经在其他地方加载可使用面积检测
    65                 newWidth * newHeight > 1024
    66             ) {
    67                 ready.call(img);
    68                 onready.end = true;
    69             };
    70         };
    71         onready();
    72         
    73         // 完全加载完毕的事件
    74         img.onload = function () {
    75             // onload在定时器时间差范围内可能比onready快
    76             // 这里进行检查并保证onready优先执行
    77             !onready.end && onready();
    78         
    79             load && load.call(img);
    80             
    81             // IE gif动画会循环执行onload,置空onload即可
    82             img = img.onload = img.onerror = null;
    83         };
    84 
    85         // 加入队列中定期执行
    86         if (!onready.end) {
    87             list.push(onready);
    88             // 无论何时只允许出现一个定时器,减少浏览器性能损耗
    89             if (intervalId === null) intervalId = setInterval(tick, 40);
    90         };
    91     };
    92 })();

    调用例子:

    imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
        alert('size ready: width=' + this.width + '; height=' + this.height);
    });

    是不是很简单?这样的方式获取摄影级别照片尺寸的速度往往是onload方式的几十多倍,而对于web普通(800×600内)浏览级别的图片能达到秒杀效果。看了这个再回忆一下你见过的web相册,是否绝大部分都可以重构一下呢?好了,请观赏令人愉悦的 DEMO :

    http://www.planeart.cn/demo/imgReady/

    (通过测试的浏览器:Chrome、Firefox、Safari、Opera、IE6、IE7、IE8)

    还有一个jquery图片预加载函数:

     1 (function($) {
     2     var imgList = [];
     3     $.extend({
     4         preload: function(imgArr, option) {
     5             var setting = $.extend({
     6                 init: function(loaded, total) {},
     7                 loaded: function(img, loaded, total) {},
     8                 loaded_all: function(loaded, total) {}
     9             }, option);
    10             var total = imgArr.length;
    11             var loaded = 0;
    12  
    13             setting.init(0, total);
    14             for(var i in imgArr) {
    15                 imgList.push($("<img />")
    16                     .attr("src", imgArr[i])
    17                     .load(function() {
    18                         loaded++;
    19                         setting.loaded(this, loaded, total);
    20                         if(loaded == total) {
    21                             setting.loaded_all(loaded, total);
    22                         }
    23                     })
    24                 );
    25             }
    26  
    27         }
    28     });
    29 })(jQuery);

    调用方法:

     1 $(function() {
     2     $.preload([
     3         "http://farm3.static.flickr.com/2661/3792282714_90584b41d5_b.jpg",
     4         "http://farm2.static.flickr.com/1266/1402810863_d41f360b2e_o.jpg"
     5     ], {
     6         init: function(loaded, total) {
     7             $("#indicator").html("Loaded: "+loaded+"/"+total);
     8         },
     9         loaded: function(img, loaded, total) {
    10             $("#indicator").html("Loaded: "+loaded+"/"+total);
    11             $("#full-screen").append(img);
    12         },
    13         loaded_all: function(loaded, total) {
    14             $("#indicator").html("Loaded: "+loaded+"/"+total+". Done!");
    15         }
    16     });
    17 });

    这个来自这里 http://ditio.net,貌似是作者的一个插件中的一段代码。
    支持三个回调函数:加载前、单个图片加载完成、全部图片加载完成。原作者还给了个演示网页,看演示网页的源代码就明白了。

    简单实例:

  • 相关阅读:
    jquery.stop()停止动画
    字符串转义
    CSS规范 (命名)- 分类方法
    inline-block 间距
    jquery中offset(),position()
    PHP把数组转换为JSON字符串
    json对象
    C#-静态实例
    C#-readonly与const区别
    SQL-事务隔离级别与锁
  • 原文地址:https://www.cnblogs.com/xingmeng/p/3372666.html
Copyright © 2011-2022 走看看