0.1.2 • Published 5 years ago

lh-prelazy v0.1.2

Weekly downloads
3
License
ISC
Repository
github
Last release
5 years ago

This is a preload and lazyload tool

🏠 Homepage

Example

Explain

优化页面加载速度、减轻服务器压力、节约流量、提高用户体验

Install

yarn add lh-prelazy --save (推荐)

cnpm i lh-prelazy --save

npm i lh-prelazy --save

Usage

HTML-预加载 1. 首先定义您的HTML代码,如果您需要预加载,必须要有 #preloading 容器来管理您的预加载动画。

  • Tips
  <div id="preloading">
    <!-- 预加载动画 -->
  </div>

  <div id="container">
    <!-- 内容 -->
  </div>
  • 为什么必须要用#preloading 容器来管理您的预加载动画。
  您只要规定该预加载容器`#preloading`,我们会根据预加载结束后,隐藏您的预加载动画。
  document.getElementById('preloading').style.display = 'none'
  1. 设置您的首屏元素属性为pre="preloading",预加载动画需要等待的预加载元素。
  • Tips
  <img src="./images/1.jpeg" alt="pre1" pre="preloading">
  • 为什么必须要用pre="preloading",来设置您的预加载元素属性。
  我们将会筛选判断您设置的首屏预加载元素是否加载成功,以此隐藏与加载动画。
  preItem[i].onload = function () {
    if (preItem.length === imgLoad.length) {
      preloadElm.style.display = 'none'
    }
  }

HTML-懒加载 1. 设计您的懒加载图片 src 设置为 data-src && 设计您的元素类名为 .lazy

  • Tips
  <img data-src="./images/1.jpeg" alt="pre1" class="lazy">
  • 为什么设置data-sr .lazy
  我们将筛选您的懒加载元素,根据元素是否出现在视口中,动态将 data-src -> src
  if (lazyItem[i].getAttribute('pre') || lazyItem[i].offsetTop < seeHeight + scrollTop){}
  lazyItem[i].setAttribute('src', lazyItem[i].getAttribute('data-src'));
  1. 设计您的懒加载展示动画,格式必须为 .lazy-${animate}, animate为你自己设置的动画类名。
  • Tips
  <img data-src="./images/1.jpeg" alt="pre1" class="lazy lazy-fadeIn">
  
  @keyframes fadeIn {
    from {
        opacity: 0;
        visibility: hidden;
    }
    to {
        opacity: 1;
        visibility: visible;
    }
  }
  .fadeIn {
    animation-name: fadeIn;
    animation-duration: 2s;
  }
  • 为什么要这样写?
  我们动态会将您设置的`.lazy-${animate}`转化为 `.animate`
   const setClassName = () => { // lazy-fadeIn -> fadeIn
     let lazyClassStrs = lazyItem[i].getAttribute('class');
     let lazyClassArr = lazyClassStrs.split(' ');
     for (let item of lazyClassArr) {
       if (item.includes('lazy-')) {
         let classAnimate = item.substr(5);
         lazyItem[i].className += ` ${classAnimate}`;
       };
     };
   };

css 1. 建议您的预加载容器这样设计。

    #preloading {
      display: block;
      position: fixed;
      z-index: 999;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      width: 100vw;
      height: 100vh;
      background-color: #374140;
    }
  1. 建议您的预加载动画可从以下查找并设计。
  2. 注意: 在设计像fadein类似动画时,必须使用visibility:hidden -> visibility:visible进行显示隐藏。
  采用offsetTop去观察元素是否出现在视口,如果您使用display:none,我们检测不到元素的位置。

图片加载失败替代方案

  new Prelazy({
    errorSrc: '替代图片加载不出来的背景图.png'
  })

js 1. 引入我们已经下好的依赖。

  import Prelazy from 'lh-prelazy'
  new Prelazy({
    errorSrc: '../images/error.png'
  })

Author

👤 LOUSANPANG

🤝 Contributing

Contributions, issues and feature requests are welcome!Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!

📝 License

Copyright © 2019 LOUSANPANG. This project is ISC licensed.