Vue实现懒加载

方式一. 使用第三方库intersection-observer-polyfill

1. 安装工具依赖

npm i intersection-observer-polyfill

2. 定义懒加载规则

import IntersectionObserver from 'intersection-observer-polyfill';

let callback = null;

IntersectionObserver.prototype.POLL_INTERVAL = 50;
const observer = new IntersectionObserver((entries) => {
  entries.forEach((el) => {
    if (el.intersectionRatio > 0) {
      if (callback) callback(el.target);
      observer.unobserve(el.target);
    }
  });
}, {
  rootMargin: '0px -100px 0px 0px',
  threshold: 0.1, // 元素出现的阈值
});
// observer.POLL_INTERVAL = 50

export const observerBox = function (target, fn) {
  observer.observe(target);
  callback = fn;
};

3. 懒加载元素设置

observerBox(this.$refs.lazyElement, (target) => {
      // todo something
    });

方式二:原生实现元素是否在可视区

计算视口与元素距离,视口可视区滚动监听时计算需要注意要节流

 /**
  * 获取窗口滚动条的上边距
  * @return {int} 上边距
  */
function getScrollTop() {
      return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    }

/**
 * 获取窗口可见高度
 * @return {int} 高度
 */
 getClientHeight: function () {
      return document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight;
 }


function checkElementClientVisible($el) {
      var boxTop = $el.offset().top;
      var boxBottom = boxTop + $el.height();
      var scrollTop = getScrollTop();
      var clientBottom = scrollTop + getClientHeight();


      // 元素在可视区域内
      if ((boxTop > scrollTop && boxTop < clientBottom) || (boxBottom > scrollTop && boxBottom < clientBottom)) {
        return true;
      }


      return false;
    }

方式三:vue-lazyload 插件实现

缺点全局引入

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值