load预加载简单实现

很久没写博客了 昨天在写页面的时候 突然想起一个页面预加载的东西 试试,刚好有朋友经常接触微信活动页面  就聊了一下思路。

页面资源加载就是三个 图片 CSS JS

现在最方便的就是判断图片加载完毕来计算进度(JS也可以计算CSS 和JS 文件是否加载完毕了,考虑loading页面等待时间不能太长,所以忽略了CSS和JS,只判断load页面的下一个页面所需要的图片加载完毕来计算进度)

imgae的onload方法就是代表image加载成功了所执行的方法。这样我们就好办了。每次加载一张 我们就 定义一个变量 add++,然后问题来了,我们实现的逻辑最好写在头部,用window.onload的话必须等待所有资源和DOM加载完毕执行,jquery的$(function(){//})很好的避免了这个问题,只加载DOM完毕就执行,还好HTML5给了高级浏览器一个福利:

DOMContentLoaded
DOM加载之后资源加载之前执行。这样方法很好的解决了我们loading页面需要操作一些DOM而undnfined的错误。

下面看image进行逻辑计算进度条代码

         /* 
* @Author: Mark
* @Date:   2015-10-22 10:39:35
* @Last Modified by:   Mark
* @Last Modified time: 2015-10-22 11:07:11
* @param 可选 obj 如果存在就设置DOM class和ID需要加上前缀,如果不存在就填写null
* @param 必填 imgs 一组图片的数组地址
* @param 必填 callBack 是图片加载完毕执行的回调函数
*/
var lyloadimg=(function(){
    function lyimg(obj,imgs,callBack){
        this.opt_num=null;
        this.opt_gress=null;
        this.opt_aver=Math.floor(100/imgs.length);
        this.opt_imgs=imgs;
        this.opt_dom=Object.prototype.toString.call(obj).slice(8,-1)=="String"?document.querySelector(obj):null;
      
        this.callBack=callBack;
        this.imgEach();
    }
    lyimg.prototype={
        constructor:"lyimg",
        setText:function(ct){
            this.opt_dom?(this.opt_dom.innerText=ct):false;
        },
        imgEach:function(){
            var that=this;
            this.setText(0);
            for (var i = 0; i < this.opt_imgs.length; i++) {
                var imgr=new Image();
                    imgr.src=this.opt_imgs[i];
                    imgr.οnlοad=function(){
                        that.opt_num++;
                        that.comter(this,that.opt_num);
                    }
            };
        },
        comter:function(imgpt,numlg){
            var that=this,_this=imgpt;
                _this.timer=setInterval(function(){
                    that.opt_gress++;
                    that.setText(that.opt_gress);
                    if(that.opt_gress>=(that.opt_aver*numlg)){
                        clearInterval(_this.timer);
                        if(numlg==that.opt_imgs.length){
                           that.ovload(that.opt_gress);
                        }
                    }
                },1000/60)
        },
        ovload:function(Count){
            if(Count<=100){
                Count=100;
                this.setText(Count);;
            }
            this.callBack();
        }
    }
    return lyimg;
})()

使用在Head里面:

            document.addEventListener('DOMContentLoaded',function(){
                 new lyloadimg(".s",imgArray,function(){
                    console.log("img loading OK");
                 });
            },false);

然后我看了一下网上有 seajs处理判断CSS文件是否加载完毕的代码,利用了判断link节点上的sheet属性来知道CSS文件是否加载完毕,代码如下:

       function loadCss(src,fn){
            var node=document.createElement('link');
            node.rel='stylesheet';
            node.href=src;
            document.head.insertBefore(node,document.head.firstChild);
            if(node.attachEvent){
                node.attachEvent('onload', function(){fn(null,node)});
            }else{
               setTimeout(function() {
                 poll(node, fn);
               }, 0); // for cache
            }
            function poll(node,callback){
                var isLoaded = false;
                if(/webkit/i.test(navigator.userAgent)) {//webkit
                    if (node['sheet']) {
                        isLoaded = true;
                      }
                }else if(node['sheet']){// for Firefox
                    try{
                        if (node['sheet'].cssRules) {
                              isLoaded = true;
                        }
                      }catch(ex){
                        // NS_ERROR_DOM_SECURITY_ERR
                        if (ex.code === 1000) {
                             isLoaded = true;
                        }
                    }
                }
                if(isLoaded){
                    setTimeout(function(){
                        callback(null,node);
                    },1);
                }else{
                    setTimeout(function(){
                        poll(node,callback);
                    },10);
                }
            }
            node.onLoad=function(){
                fn(null,node);
            }
        }


关于司徒正美 他的 JS时候加载完毕的逻辑判断是根据 onload或者 onreadystatechange 来处理的,逻辑和上面两个的差不多,代码如下:

       function loadScript(src,fn){
            var node = document.createElement("script");
            node.setAttribute('async','async');
            var timeID
            var supportLoad = "onload" in node
            var onEvent = supportLoad ? "onload" : "onreadystatechange"
            node[onEvent] = function onLoad() {
                if (!supportLoad && !timeID && /complete|loaded/.test(node.readyState)) {
                    timeID = setTimeout(onLoad)
                    return
                }
                if (supportLoad || timeID) {
                    clearTimeout(timeID)
                    fn(null,node);
                }
            }
            document.head.insertBefore(node, document.head.firstChild);
            node.src=src;
            node.οnerrοr=function(e){
                fn(e);
            }
        }

今日分享完毕,最近实在没有怎么样钻研动画之类的库,在了解gulp前端处理的工具,感觉颓废了,所以博客很久才更新一次。希望尽快恢复脸皮厚的钻研动画的状态。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值