# Scrollload **Repository Path**: ajaxZheng/Scrollload ## Basic Information - **Project Name**: Scrollload - **Description**: scroll load more data 滚动加载更多数据 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2017-03-08 - **Last Updated**: 2021-02-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 初衷 如今移动端站点越来越多,滚动到底部加载数据的需求应该非常的常见,即使现在很多pc站点也会有这样的需求,比如百度首页就有。但是我却一直没找到特别好用的插件,基本上的插件都依赖于jquery。我想要的很简单,方便好用可定制体积又小功能又强大的插件。 ### Scrollload.js介绍 Scrollload是一个无依赖,体积极小(压缩+gzip后不到2k),可配置性高(可以自定义加载时候动画,加载完后的dom,提前加载的距离),功能强大(能做到指定容器内的滚动,多tab的滚动,异常处理,刷新重新加载),性能好(在滚动的时候做了一些性能优化,如缓存window的高度,函数节流)的js插件。 ### 兼容性 不支持ie8及以下浏览器,其他都没有问题。如果你发现哪些浏览器上有问题,请一定要联系我。 ### 示例 [无任何效果](https://fa-ge.github.io/Scrollload/dist/feature-demos/demo1/index.html) [有loading动画一](https://fa-ge.github.io/Scrollload/dist/loading-demos/twoBallsSwing/index.html) [有loading动画二(百度移动端)](https://fa-ge.github.io/Scrollload/dist/loading-demos/baidu-mobile/index.html) [多个tab效果](https://fa-ge.github.io/Scrollload/dist/feature-demos/demo2/index.html) [div容器中的滚动加载](https://fa-ge.github.io/Scrollload/dist/feature-demos/demo3/index.html) ***[左右滑动tab并且滚动加载](https://fa-ge.github.io/Scrollload/dist/complex-demos/swiper-tab/index.html)***——复杂示例 [异常处理](https://fa-ge.github.io/Scrollload/dist/feature-demos/demo4/index.html) [点击刷新重新加载](https://fa-ge.github.io/Scrollload/dist/feature-demos/demo5/index.html) [示例源码](https://github.com/fa-ge/Scrollload/tree/master/src) ### 实现原理 首先得区分一下全局滚动和局部滚动。 全局滚动:滚动条在body或者body上层元素或者window上 局部滚动:滚动条在body里的元素上。 由于浏览器兼容性原因,全局滚动都应该在window上绑定滚动事件。而局部滚动则是在产生滚动条那个元素上绑定滚动事件就可以了。之后我会把产生滚动条的元素统称为视窗。 核心逻辑其实就是判断是否滚动到底部。这个底部指的是列表底部的那个加载中动画div的元素的顶部,之后我都会叫他底部DOM。 ```javascript function isBottom() { //win指的是视窗,bottomDom指的是底部DOM const {win, bottomDom, windowHeight} = this let bottomDomTop = bottomDom.getBoundingClientRect().top let winHeight if (win === window) { winHeight = windowHeight } else { const winRect = win.getBoundingClientRect() winHeight = winRect.height bottomDomTop = bottomDomTop - winRect.top } //threshold指的是提前加载的距离 return bottomDomTop - winHeight <= this.options.threshold } ``` 原理很简单,我判断底部DOM的上边框到视窗上边框的距离是否要大于视窗的高度。就那么简单。这边有做一个小小的性能优化,因为isBottom函数是scroll事件和resize事件的回调函数,执行频率相当高。函数节流当然有做,这边还对window.innerHeight这个值做了缓存。实在没必要每次执行这个函数都去获取以下window的高度。除去给window.innerHeight直接赋值外,我能想到能改变window的高度的一定会触发resize.所以我在resize事件的回调中更新window.innerHeight就可以了。 详细的源码请看 [源码](https://github.com/fa-ge/Scrollload/blob/master/src/Scrollload.js) ### 安装 ```javascript npm install Scrollload --save ``` ### 使用 如果你没有用模块管理,直接从window对象下取Scrollload对象也是可以的,打包后的js放在lib目录下,可以直接用script标签引入 同时支持模块引入 ```javascript //ES6 import Scrollload from 'Scrollload' //commonjs const Scrollload = require('Scrollload').default ``` 当然也支持amd,不过我没用过。 真正用起来也非常简单。记住一点。插件会把底部DOM插入到container最后一个子节点之后。 假如你的dom结构是以下这样的 ```html