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: only called 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 the loading diagram of an image
        let defaultSrc = options.default;
        Vue.directive('lazy',{
            bind(el,binding){
                LazyLoad.init(el,binding.value,defaultSrc);
            },
            inserted(el){
                // Compatible processing
                if('IntersectionObserver' in window){
                    LazyLoad.observe(el);
                }else{ LazyLoad.listenerScroll(el); }}})},/ / initialization
    init(el,val,def){
        // data-src stores the true SRC
        el.setAttribute('data-src',val);
        // Set SRC to the loading diagram
        el.setAttribute('src',def);
    },
    // Use IntersectionObserver to monitor EL
    observe(el){
        let io = new IntersectionObserver(entries= > {
            let realSrc = el.dataset.src;
            if(entries[0].isIntersecting){
                if(realSrc){
                    el.src = realSrc;
                    el.removeAttribute('data-src'); }}}); io.observe(el); },// Listen for scroll events
    listenerScroll(el){
        let handler = LazyLoad.throttle(LazyLoad.load,300);
        LazyLoad.load(el);
        window.addEventListener('scroll',() => {
            handler(el);
        });
    },
    // Load the real image
    load(el){
        let windowHeight = document.documentElement.clientHeight
        let elTop = el.getBoundingClientRect().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'); }}},/ / throttling
    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

The code address

Github.com/erdong0604/…

The last

If there is any error in this article, please be sure to leave a comment to correct, thank you very much.

Give me a thumbs up, let’s study together and make progress together.