大家都知道lazyload.js预加载技术,它极大的加快了网页打开速度,但是今天我们所讲的并不是介绍lazyload.js是如何工作的,而是重新认识一款新的优化神器-BigRender,从名字是可以很清楚的理解这一技术特点,bigrender顾名思义是对大页面渲染的优化。bigrender的原理是通过某种方式,将首屏不需要的html代码先存放起来。渲染好首屏后,再将存储好的html代码逐步渲染出来。
效果:
打开天猫首页,首屏已经渲染好了,其他的内容,通过一个gif图来表示,这些没有被渲染的内容都被保存在一个隐藏的textarea框内,这么做的好处是显而易见,减少DOM节点,加快首屏的渲染,提高用户体验,如果首屏够长,内容够多,都可以进行这样的处理,速度那是没得说!
bigrender使用方法:
js代码
(
function
($){
$.fn.bigrender =
function
(opts){
var
winHeight = document.documentElement.clientHeight;
var
sum = 0;
var
count = 0;
var
flash =
new
Array();
// 'class' 是textarea父节点的类;'textarea' 是textarea标签的类;'threshold'是距离进入屏幕还有150像素就开始渲染;'remove'是否删除textarea标签
options = $.extend({
'class'
:
'.br-warp'
,
'textarea'
:
'.br-rendered'
,
'threshold'
: 150,
'remove'
:
true
,
},opts);
$brenders = $(options.class);
// 渲染首屏的内容
initBigrender();
// 绑定滚动条事件
scrollDisplay();
// 函数定义
function
initBigrender(){
$brenders.each(
function
(n,object){
sum++;
if
(isRender($(
this
))){
display($(
this
));
count++;
flash[n] =
true
;
}
else
{
flash[n] =
false
;
}
});
}
// 判断时候需要渲染
function
isRender(object){
offsetTop = object.offset().top;
ojh = object.outerHeight(
true
);
st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
if
(offsetTop+ojh+options.threshold >= st && offsetTop-options.threshold < (st+winHeight)){
return
true
;
}
else
return
false
;
}
// 渲染textarea内的html代码
function
display(object){
$display = object.find(options.textarea).eq(0);
if
(options.remove){
object.append($display.val());
$display.remove();
}
else
{
object.append($display.val());
}
}
// 屏幕绑定滚动条事件,当待渲染的内容进入可视屏幕就触发isRender函数
function
scrollDisplay(){
$(window).scroll(
function
() {
event.preventDefault();
if
(count < sum){
$brenders.each(
function
(n,object){
if
(flash[n] ==
false
){
if
(isRender($(
this
))){
display($(
this
));
count++;
flash[n] =
true
;
}
else
{
flash[n] =
false
;
}
}
});
}
});
}
};
})(jQuery);
|
插件调用
$.fn.bigrender({
'threshold'
: 100});
// 提前100像素开始渲染
|
渲染前html
<
article
class
=
"br-warp"
style
=
"min-height: 300px;"
><
textarea
class
=
"br-rendered"
style
=
"display:none"
><
div
>html内容。。。</
div
></
textarea
></
article
>
|
渲染后html
<
article
class
=
"br-warp"
style
=
"min-height: 300px;"
><
div
>html内容。。。</
div
></
article
>
|
优缺点 & 适用场景
–优点很明显,因为减少了首屏 DOM 的渲染,所以能加快首屏加载的速度,并且能分块加载 js/css,非常适用于一些模块区分度很高的网站。
–缺点是需要更改 DOM 结构(DOM 节点的替换和渲染),可能会引起一些重排和重绘。
具体查看插件主页:https://github.com/hanzichi/hanzichi.github.io/tree/master/2016/bigrender