大数据前端优化策略

1、策略

将数据展示区域分为3个部分,上屏、下屏和中屏。中屏为可视区域,上下屏缓存即将加载的内容。缓存的原因是,在我们滚动滚动条的时候,js 需要时间来拼凑字符串(或者创建 Node ),这个时候浏览器还来不及渲染,所以会出现临时的空白,这种体验是相当不好的。

上屏缓存内容
sh = 一条数据的高度
蓝色为可视区域
 
下屏缓存内容

 

2、算法说明

 

1)可视区域的高度:height = 300;

2)首页确认展示一条数据的高度:sh = 20;

3)计算可视区域最多展示多少条数据:showLen = parseInt(height/sh);

4)滚动条滚动的高度:srollTop = $(this).scrollTop();

5)计算展示数据开始/结束的下标:startIndx = parseInt(slTop/sh);endIndx = Math.min(startIndx + showLen*2, total - 1);

6)插入DOM;

7)滚动条滚动时,将不在三个区域中的dom从页面移除;

3、DEMO
<div id="box"></div>
#box {position: relative; height: 300px; width: 200px; border:1px solid #CCC; overflow: auto}
#box div { position: absolute; height: 20px; width: 100%; left: 0; overflow: hidden; font: 16px/20px Courier;}
var sh = 20, // 一条数据占据的高度
    total = 10000, // 1W条数据
    box = $('#box'),// 展示数据的box
    height = box.height(), // 可视区域高度
    data = [], // 数据源
    showLen = parseInt(height/sh); // 可视区域容纳N条数据

// 初始化数据源
for(var a=0;a<total;a++){
    data.push('item-show: '+a);
}

box.scroll(function(){
    var i=0,
        s,
        childList = box.find('div'),
        srollTop = $(this).scrollTop(),
        startIndx = Math.max(parseInt(srollTop/sh),0),
        endIndx = Math.min(startIndx + showLen*2, total - 1);
    
    // 生成数据列表
    for(s=startIndx;s<endIndx;s++){
        // 判断插入的数据是否存在
        if(!childList[s]){
            insert(s);
        }else{
            var exIdx = $(childList[s]).attr('idx');
            // 存在的DOM下标与即将插入的数据下标不一致则追加DOM
            if(exIdx!=s){
                insert(s);
            }
        }
    }
    // 移除三屏外的DOM
    while(child=childList[i++]){
        var index = $(child).attr('idx');
        if((index>endIndx||index<Math.max(startIndx-15,0))&&index!=total-1){
           $(child).remove();
        }
    }
    
    
})
// 追加数据方法
function insert(i){
    var txt = data[i];
    var top = i*sh;// 设置top属性,让滚动条拉长,让用户感觉存了很多条数据
    var str = '<div style="top:'+top+'px" idx="'+i+'">'+txt+'</div>';
    var child = box.find('div');
    box.append(str);           
}

box.scroll()
// 默认插入最后一条数据,设置top属性,让滚动条拉长
insert(total-1)

参考文档:http://www.cnblogs.com/hustskyking/p/million-data-show-in-front-end.html

posted @ 2014-10-17 15:17  Scool.Miss  阅读(448)  评论(0编辑  收藏  举报