javascript图片预加载技术

本文介绍了一种使用JavaScript获取图片尺寸的预加载技术,通过监测图片加载过程中的尺寸变化来提前获取图片的真实尺寸,从而提高用户体验。
图片预加载技术的典型应用:

如lightbox方式展现照片,无疑需要提前获得大图的尺寸,这样才能居中定位,由于javascript无法获取img文件头数据,必须等待其加载完毕后才能获取真实的大小然后展示出来,所以lightbox显示的图片的速度体验要比直接输出的差很多,而本文说提到的预加载技术主要针对获取图片尺寸。

一段典型的使用预加载获取图片大小的例子:

QUOTE:
var imgLoad = function (url, callback) {
        var img = new Image();

        img.src = url;
        if (img.complete) {
                callback(img.width, img.height);
        } else {
                img.onload = function () {
                        callback(img.width, img.height);
                        img.onload = null;
                };
        };

};

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

一、结合flash加载图片,获取图片头部数据的尺寸

flash虽然很强大,但它与生俱来的缺点让人爱恨交织,加上很多移动设备不支持falsh无疑更是致命的伤,还是放弃吧。

二、在服务端保存图片尺寸数据

这里不得不提到腾讯Qzone的lightbox相册,它就是这样做的。它能在图片没有加载完全的时候就居中放大图片,速度与优雅基本兼得。不过它仍然难以避免blog插入的外链图片的问题,也只能按传统的方式加载完毕才能展示。

三、javascript通过占位方式获取图片头部数据的尺寸

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

实现代码:
(0.3版本更新了图片加载进程中的判断,优化多个图片同时监听的性能)

QUOTE:
// imgReady event - 2011.04.02 - TangBin - MIT Licensed
/**
* 图片头数据加载就绪事件
* @see                 http://www.planeart.cn/?p=1121
* @param        {String}        图片路径
* @param        {Function}        尺寸就绪 (参数1接收width; 参数2接收height)
* @param        {Function}        加载完毕 (可选. 参数1接收width; 参数2接收height)
* @param        {Function}        加载错误 (可选)
*/
var imgReady = (function () {
        var list = [], intervalId = null,

        // 用来执行队列
        tick = function () {
                var i = 0;
                for (; 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 check, width, height, newWidth, newHeight,
                        img = new Image();

                img.src = url;

                // 如果图片被缓存,则直接返回缓存数据
                if (img.complete) {
                        ready(img.width, img.height);
                        load && load(img.width, img.height);
                        return;
                };

                // 检测图片大小的改变
                width = img.width;
                height = img.height;
                check = function () {
                        newWidth = img.width;
                        newHeight = img.height;
                        if (newWidth !== width || newHeight !== height ||
                                // 如果图片已经在其他地方加载可使用面积检测
                                newWidth * newHeight > 1024
                        ) {
                                ready(newWidth, newHeight);
                                check.end = true;
                        };
                };
                check();

                // 加载错误后的事件
                img.onerror = function () {
                        error && error();
                        check.end = true;
                        img = img.onload = img.onerror = null;
                };

                // 完全加载完毕的事件
                img.onload = function () {
                        load && load(img.width, img.height);
                        !check.end && check();
                        // IE gif动画会循环执行onload,置空onload即可
                        img = img.onload = img.onerror = null;
                };

                // 加入队列中定期执行
                if (!check.end) {
                        list.push(check);
                        // 无论何时只允许出现一个定时器,减少浏览器性能损耗
                        if (intervalId === null) intervalId = setInterval(tick, 40);
                };
        };
})();

 

 

DEMO :

<! DOCTYPE html >  
< html xmlns = " http://www.w3.org/1999/xhtml " >  
< head >  
< meta http - equiv = " Content-Type "  content = " text/html; charset=utf-8 "   />  
< title > img ready demo </ title >  
< script >
//  imgReady event - 2011.04.02 - TangBin - MIT Licensed
/*
*
 * 图片头数据加载就绪事件
 * @see        [url]
http://www.planeart.cn/?p=1121 [/url]
 * @param    {String}    图片路径
 * @param    {Function}    尺寸就绪 (参数1接收width; 参数2接收height)
 * @param    {Function}    加载完毕 (可选. 参数1接收width; 参数2接收height)
 * @param    {Function}    加载错误 (可选)
 
*/
var imgReady 
=  (function () {
    var list 
=  [], intervalId  =   null ,

    
//  用来执行队列
    tick  =  function () {
        var i 
=   0 ;
        
for  (; 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 check, width, height, newWidth, newHeight,
            img 
=   new  Image();

        img.src 
=  url;

        
//  如果图片被缓存,则直接返回缓存数据
         if  (img.complete) {
            ready(img.width, img.height);
            load 
&&  load(img.width, img.height);
            
return ;
        };

        
//  检测图片大小的改变
        width  =  img.width;
        height 
=  img.height;
        check 
=  function () {
            newWidth 
=  img.width;
            newHeight 
=  img.height;
            
if  (newWidth  !==  width  ||  newHeight  !==  height  ||
                
//  如果图片已经在其他地方加载可使用面积检测
                newWidth  *  newHeight  >   1024
            ) {
                ready(newWidth, newHeight);
                check.end 
=   true ;
            };
        };
        check();

        
//  加载错误后的事件
        img.onerror  =  function () {
            error 
&&  error();
            check.end 
=   true ;
            img 
=  img.onload  =  img.onerror  =   null ;
        };

        
//  完全加载完毕的事件
        img.onload  =  function () {
            load 
&&  load(img.width, img.height);
            
! check.end  &&  check();
            
//  IE gif动画会循环执行onload,置空onload即可
            img  =  img.onload  =  img.onerror  =   null ;
        };

        
//  加入队列中定期执行
         if  ( ! check.end) {
            list.push(check);
            
//  无论何时只允许出现一个定时器,减少浏览器性能损耗
             if  (intervalId  ===   null ) intervalId  =  setInterval(tick,  40 );
        };
    };
})();
</ script >  
< style >  
/* demo style */
body { font:12px 
' Microsoft Yahei ' , Tahoma, Arial; _font - family:Tahoma, Arial; }
a { color:#0259C4; }
a:hover { color:#
900 ; }
.tips { color:#CCC; }
h1 { font
- family: ' Constantia ' ;}
#path { width:36em; padding:5px; border:2px solid #0259C4; background:#FAFAFA;
- webkit - border - radius:3px;  - moz - border - radius:3px; border - radius:3px; }
#path:focus { background:#FFFFF7; outline:
0 ; }
#submit { padding:5px 10px; border:2px solid #0259C4; background:#0259C4; color:#FFF; 
- webkit - border - radius:3px;  - moz - border - radius:3px; border - radius:3px; cursor:pointer; }
#submit.disabled { background:#D7D7D7; color:#ABABAB; border
- color:#ABABAB; cursor: default ; }
</ style >  
< script >  
/*  demo script  */
window.onload 
=  function () {
    
    var $ 
=  function (id) {
        
return  document.getElementById(id);
    };
    
    var Timer 
=  function (){
        
this .startTime  =  ( new  Date()).getTime();
    };
    Timer.prototype.stop 
=  function(){
        
return  ( new  Date()).getTime()  -   this .startTime;
    };
    
    var imgUrl,
        checkboxFn,
        path        
=  $( ' path ' ),
        submit        
=  $( ' submit ' ),
        checkbox    
=  $( ' checkbox ' ),
        clsCache    
=  $( ' clsCache ' ),
        status        
=  $( ' status ' ),
        statusReady    
=  $( ' statusReady ' ),
        statusLoad    
=  $( ' statusLoad ' ),
        imgWrap        
=  $( ' imgWrap ' );
    
    submit.disabled 
=   false ;    
    submit.onclick 
=  function () {
        var that 
=   this ,
            time 
=   new  Timer();
        
        imgUrl 
=  path.value;
        status.style.display 
=   ' block ' ;
        statusLoad.innerHTML 
=  statusReady.innerHTML  =   ' Loading... ' ;
        
        
//  参数: 图片地址, 尺寸就绪事件, 完全加载事件, 加载错误事件
        imgReady(imgUrl, function (width, height) {
            statusReady.innerHTML 
=   ' 耗时  '   +  (time.stop()  /   1000 + '  秒. 宽度:  '   +  width  +   ' ; 高度:  '   +  height;
            checkboxFn();
        }, function (width, height) {
            statusLoad.innerHTML 
=   ' 耗时  '   +  (time.stop()  /   1000 + '  秒. 宽度:  '   +  width  +   ' ; 高度:  '   +  height;
        }, function () {
            statusLoad.innerHTML 
=  statusReady.innerHTML  =   ' 耗时  '   +  (time.stop()  /   1000 + '  秒. 加载错误! ' ;
        });
    };
    
    clsCache.onclick 
=  function () {
        var value 
=  path.value;
        path.value 
=  (value.split( ' ? ' )[ 1 ?  value.split( ' ? ' )[ 0 ] : value)  +   ' ? '   +   new  Date().getTime();
        status.style.display 
=   ' none ' ;
        imgWrap.innerHTML 
=   '' ;
        
return   false ;
    };
    
    checkbox.onclick 
=  checkbox.onchange  =  checkboxFn  =  function () {
        imgWrap.innerHTML 
=  imgUrl  &&  checkbox. checked   ?   ' <img src=" '   +  imgUrl  +   ' " /> '  :  '' ;
    };
    checkbox.
checked   =   false ;
 
    $(
' down ' ).onclick  =  function () {
        window.open(
this .getAttribute( ' data-href ' ||   this .href);    
        
return   false ;
    }
};
 
</ script >  
</ head >  
 
< body >  
< div  class = " demoInfo " >  
< h1 > imgReady </ h1 >  
< class = " tips " > 图片头数据加载就绪事件 </ p >  
< p >< strong > 下载: </ strong ></ p >  
< p >< a id = " down "  data - href = " http://goo.gl/KBp5a "  href = " http://www.planeart.cn/demo/imgReady/imgReady.js " > imgReady.js </ a ></ p >  
< p >< strong > 相关文章: </ strong ></ p >  
< p >< a href = " http://www.planeart.cn/?p=1121 " > 再谈javascript图片预加载技术 </ a ></ p >  
< p >< strong > 演示: </ strong ></ p >  
</ div >  
 
< div style = " height:40px; line-height:40px; " >< input type = " text "  id = " path "  value = " http://www.planeart.cn/demo/imgReady/vistas24.jpg "   />   < input type = " button "  id = " submit "  value = " 加 载 "   />   < label >< input id = " checkbox "  type = " checkbox " > 显示图片 </ label >  
< a id = " clsCache "  href = " # "  style = " color:#0259C4; " > 清空缓存 </ a >< em  class = " tips " > (浏览器会缓存加载过后的图片) </ em ></ div >  
< div id = " status "  style = " display:none " >  
  
< p >< strong > 通过文件头信息获取尺寸: </ strong >   < span id = " statusReady " ></ span >< p >  
    
< p >< strong > 通过加载完毕后获取尺寸: </ strong >   < span id = " statusLoad " ></ span ></ p >  
</ div >  
 
< div id = " imgWrap " ></ div >  
 
< div >< script type = " text/javascript " > document.write( ' <scr ' + ' ipt src="http://s86.cnzz.com/stat.php?id=1581115&web_id=1581115" type="text/javascript" charset="gb2312"></sc ' + ' ript> ' ) </ div >  
</ body >


转载于:https://www.cnblogs.com/colder/archive/2011/04/18/2019934.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值