crad.js
v1.0.0
Published
crazy load with Intersection Observer API
Downloads
5
Readme
crad.js (Cr~~azy Lo~~ad)
没错,又一个懒加载JS类库!
- crazy small:压缩后只有 1kb
- crazy simple: 一行代码就能做到初始化
- crazy fast: 感谢Intersection Observer API
crad.js能做到:懒加载图片,广告,视频和其它被Intersection Observer API支持的所有元素! 最重要的是,它效率非常高!
为什么又造个轮子?
已经有很多JS类库来解决懒加载的问题了,比如jQuery.lazyload、Unveil,基本思路就是监听滚动事件或者开启轮询定时器,然后不断调用懒加载元素的getBoundingClientRect()
。这种方式非常不好的就是每调用一次getBoundingClientRect
都会引起浏览器的重新布局(re-layout),进而加重了浏览器的执行负担,严重者就会造成页面卡顿。很显然,这样体验不好。
IntersectionObserver是为了效率和性能而生,并且率先在Chrome 51版本支持(没错,Chrome再一次领先)。现代浏览器均已支持该,哦不对,除了Safari(New IE)。IntersectionObserver能让你知道被监听的元素是否处于浏览器视窗(viewport)内。
开始使用
获取:
Yarn :
yarn add crad.js
Bower :
bower install crad.js
npm:
npm install --save crad.js
在页面头部引入:
<script type="text/javascript" src="crad.js"></script>
或者:
<script type="text/javascript" src="crad.min.js"></script>
温馨提示:crad.js支持 AMD 和 commonJS 加载方式。:)
使用
最简洁的初始化:
new Crad(); // 默认使用".crad"css选择器
也可以定制化:
new Crad({
cssSelector: '.block [attr=whatever]', // 指定需要懒加载的元素
rootMargin: '10px 0px', // 和css中的margin意义一致
threshold: 0.1 // 元素进入视窗的百分比,触发加载
})
参考:
也可以针对懒加载元素自定义:
var crad = new Crad();
crad.load = function(el) {
console.log('正在加载...');
// 自定义加载
// e.g. el.src = el.dataset.src;
}
浏览器支持
IntersectionObserver支持情况。 如果考虑低版本浏览器的支持,可以瞅瞅W3C出品的polyfill。
License
Copyright (c) 2017 Tristan Licensed under the MIT license.