Lazy loading definition

Lazy loading of images is lazy loading. Instead of loading all the images at once, load them when the user needs one of them, so you don’t have to request a lot of data at the same time. Load the image when it is in the viewable area.

instruction

In Vue, in addition to the commonly used V-show, V-bind and other commands, you can also customize commands. Because the custom instructions are too simple, we will only briefly describe what the resulting hook functions can do.

Bind: called only once, when the directive is bound to an element, and can be used for initialization.

Inserted: Called when the bound element is inserted into the parent node.

implementation

Create a LazyLoad folder in the Component folder and create index.js in the folder.

The code is as follows:

Const LazyLoad = {// install method install(Vue,options){// replace loading graph let defaultSrc = options.default; Vue.directive('lazy',{ bind(el,binding){ LazyLoad.init(el,binding.value,defaultSrc); }, inserted(el){// Insert (el){if(' insert Observer' in window){LazyLoad. Observe (el); }else{ LazyLoad.listenerScroll(el); }},})}, // init(el,val,def){// data-src stores true SRC el.setattribute ('data-src',val); // Set SRC to loading graph el.setattribute (' SRC ',def); }, // Use IntersectionObserver to monitor EL observe(EL){let IO = new IntersectionObserver(entries => {let realSrc = el.dataset. SRC; // Use IntersectionObserver to monitor EL observe(EL){let IO = new IntersectionObserver(entries => {let realSrc = el. if(entries[0].isIntersecting){ if(realSrc){ el.src = realSrc; el.removeAttribute('data-src'); }}}); io.observe(el); }, // listenerScroll(el){let handler = lazyload.load (lazyload.load,300); LazyLoad.load(el); window.addEventListener('scroll',() => { handler(el); }); }, / / load the real images load (el) {let windowHeight = document. The documentElement. ClientHeight let elTop = el. GetBoundingClientRect (). The top;  let elBtm = el.getBoundingClientRect().bottom; let realSrc = el.dataset.src; if(elTop - windowHeight<0&&elBtm > 0){ if(realSrc){ el.src = realSrc; el.removeAttribute('data-src'); }}}, // throttle throttle(fn,delay){let timer; let prevTime; return function(... args){ let currTime = Date.now(); let context = this; if(! prevTime) prevTime = currTime; clearTimeout(timer); if(currTime - prevTime > delay){ prevTime = currTime; fn.apply(context,args); clearTimeout(timer); return; } timer = setTimeout(function(){ prevTime = Date.now(); timer = null; fn.apply(context,args); },delay); } } } export default LazyLoad;Copy the code

use

Add it to main.js

import LazyLoad from './components/LazyLoad';

Vue.use(LazyLoad,{
    default:'https://tva1.sinaimg.cn/large/007S8ZIlgy1gfyof9vr4mj3044032dfl.jpg'
});
Copy the code

Used in components

<img v-lazy="https://tva1.sinaimg.cn/large/007S8ZIlgy1gfynwi1sejj30ij0nrdx0.jpg" />
Copy the code

The final result