原生js :图片预加载(oop)

专题中图片预加载用的比较多,每次从复的写麻烦,写一个每次引一下好了:

 

加载进度: 已加载张数/总张数+%

<!DOCTYPE HTML>
<html> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>预加载_oop</title>
    </head>
    <body>
        <div id="div1"></div>
        <script>
            //要加载的图片 ================
            var aImg1=[
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/zailaiBtn.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/yes.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/tai.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t7_a.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t7_b.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t7_t.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t3_b.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t1_b.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t4_t.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t2_b.png',
                'http://img1.cache.netease.com/f2e/health/huoyanjinjing/images/t3_t.png'
            ];
//预加载函数
function ImgLoad(o,goFn,overFn){ this.offon=0; this.ratio=0; this.o=o; this.goFn=goFn; this.overFn=overFn; this.init(); }; ImgLoad.prototype.init = function(){ var This=this; for (var i=0; i<this.o.length; i++) { this.oimg=new Image(); this.oimg.onload=function(){var _i=this; This.fnonload(_i);}; this.oimg.onerror=function(){var _i=this; This.fnerror(_i);}; this.oimg.src=this.o[i]; this.oimg.index=i; }; }; ImgLoad.prototype.fnonload = function(_i){//正确加载的 this.fnOk(); // console.log(this.ratio+'第:'+_i.index+' 正确 '+_i.src); }; ImgLoad.prototype.fnerror=function(_i){//加载错误的 this.fnOk(); // console.log(this.ratio+'第:'+_i.index+' 加载错误 '+_i.src); }; ImgLoad.prototype.fnOk = function(){ this.offon++; this.ratio=Math.ceil(this.offon/this.o.length*100); this.goFn(); if(this.offon >= this.o.length){ this.overFn();}; };

       //调用
var oLoadingL=document.querySelector('#div1'); var goIL=new ImgLoad( aImg1 //数组【图片连接,】 ,function(){oLoadingL.innerHTML+=goIL.ratio+"%<br/>";}//加载回调 ,function(){alert('预加载结束')}//完毕回调 ); </script> </body> </html>

 

posted on 2016-01-20 18:01  songyijian321  阅读(397)  评论(0编辑  收藏  举报

导航