前端入门之(vue图片加载框架完结)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vv_bug/article/details/81673559

前言: 2018已经过了一大半了,并没有感觉在本命年中有啥不顺的,每天过得还是挺开心的��,很感谢身边的朋友一路的陪伴,感恩!! 已经半年多没回家了,不久前跟麻麻发了一个视频,跟过年比,家里妹妹长了10cm,麻麻瘦了10kg,我家狗狗从小奶狗长到了30kg了,麻麻说:“你胡子长了要刮一刮了” ��! 才发现自己真的不小了~~为梦想历经沧桑、阅尽千帆、归去才发现自己早已非少年了啊!!! 不逼逼了,进入我们今天的主题哈~

前面已经写过两篇同系列的文章了,感兴趣的童鞋可以去看看哈,h5刚起步,文章纯属于个人学习笔记,大牛勿喷!

前端入门之(vue图片加载框架一)
前端入门之(vue图片加载框架二)

前端入门之(vue图片加载框架二)中最后我们已经实现了框架的基本功能,也就是placeholder(loading跟error)占位图效果.
[图片上传失败…(image-6288f8-1533729480712)]

最后还留了一个问题:
当我们的图片很多的时候,我们只需要加载我们看到的部分,当滑动到其它部分的时候再去加载(以时间换空间),现在我们是直接一出来就加载全部图片(以空间换时间), 如果是在pc端的话,我们可以直接加载全部,这样快,而且pc上貌似内存问题还不是很大的问题,但是当到手机端的时候,内存的占用直接影响的是用户体验,所以我们需要用懒加载的方式去加载图片

我们先看一下如果我们直接加载几张图片会怎么样?

<template>
  <div class="opt-container">
    <img v-lazy="{src: image}" v-for="(image,index) in images" v-bind:key="'image-'+index">
  </div>
</template>

<script>
  const IMAGES = [
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=c136f7387cfe2b79161f2f93bff6cb96&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F09%2F65%2Fb3468db29cb1.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=de941561df3b6fd53b2df9bfd6c0b187&imgtype=0&src=http%3A%2F%2Fpic43.photophoto.cn%2F20170413%2F0008118236659168_b.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283185&di=aff7e8aa60813f6e36ebc6f6a961255c&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d60f57e8a07d0000018c1bfa2564.JPG%403000w_1l_2o_100sh.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533726597165&di=198b9836a377021082281fcf0e5f3331&imgtype=0&src=http%3A%2F%2Fchongqing.sinaimg.cn%2Fiframe%2F159%2F2012%2F0531%2FU9278P1197T159D1F3057DT20140627094648.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533726597167&di=e06fc5f74fac9bb61d229249219cbe4f&imgtype=0&src=http%3A%2F%2Fimg2.ph.126.net%2FuWKrNCkdBNBPzdjxCcUl-w%3D%3D%2F6630220042234317764.jpg'
  ]
  export default {
    name: 'Lazy',
    data() {
      return {
        images: IMAGES,
        showImage: true
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .opt-container {
    font-size: 0px;
  }
</style>

可以看到,我们代码很简单,就是直接加载了5张图片,然后我们看一下流量消耗:

屏幕快照 2018-08-08 下午4.44.01.png

可以看到,我们消耗了1.3MB的流量,而且所有图片都在同一时间加载的,这才5张图片,在项目中,我们一个页面几百张图片也不是不可能哈,所以想想就有点恐怖,放到pc还好,手机上估计是要哭的节奏~ 所以我们考虑一下,当我们滑动的时候,我们滑动看到的图片才让它加载,地下未滑到图片我们就暂时不加载了.我们来试试哈~~

首先是监听窗体的滚动,因为我们这里是直接是body在滚动,所以,我们直接监听:

 mounted(){
      window.onscroll=()=>{
        console.log(window.scrollY);
      }
    }

然后我们滑动窗体:
屏幕快照 2018-08-08 下午5.01.26.png
所以我们需要在onscroll中通知所有的listener(经纪人),问一下他:“我们现在到这个位置了,你需要不需要加载?”,我们首先得通知manager(经理),然后由manager去通知listener(经纪人):
首先通知LazyDelegate,那么我们怎么拿到LazyDelegate引用呢? 我们可以在install方法执行的时候传给Vue的prototype,这样每个vue的实例都会有LazyDelegate的引用了:

import lazyDelegate from './LazyDelegate';

export default {
  install(Vue, options = {}) {
    let LazyClass = lazyDelegate(Vue);
    let lazy = new LazyClass(options);
    Vue.prototype.$Lazyload = lazy
   ...
  }
}

然后在我们demo的vue文件中:

 mounted(){
      window.onscroll=()=>{
        this.$Lazyload.lazyLoadHandler();
      }
    }

然后我们经理的lazyLoadHandler方法就会一个一个通知listener去加载图片.

 /**
     * 通知所有的listener该干活了
     * @private
     */
    _lazyLoadHandler() {
      //找出哪些是已经完成工作了的
      const freeList = []
      this.ListenerQueue.forEach((listener, index) => {
        if (!listener.state.error && listener.state.loaded) {
          return freeList.push(listener)
        }
        listener.load()
      })
      //把完成工作的listener剔除
      freeList.forEach(vm => remove(this.ListenerQueue, vm))
    }

我们在_lazyLoadHandler打个log,当我们滑动窗体的时候:

屏幕快照 2018-08-08 下午6.16.08.png

我们可以看到.回调了我们的_lazyLoadHandler方法,进而就会去通知所有的listener去加载图片:

_lazyLoadHandler() {
      ....
      this.ListenerQueue.forEach((listener, index) => {
        if (!listener.state.error && listener.state.loaded) {
          return freeList.push(listener)
        }
        listener.load()
      })
    ...
    }

前面我们说了,滑动的时候,通知listener加载图片还有一个条件,当前img是否在窗体内,是否可以见?
所以我们需要加一个判断:

_lazyLoadHandler() {
      ....
      this.ListenerQueue.forEach((listener, index) => {
        if (!listener.state.error && listener.state.loaded) {
          return freeList.push(listener)
        }
       if(是否在窗体内,是否可以见?){
          listener.load()
        }
      })
    ...
    }

转换成代码就是:


    /**
     * 通知所有的listener该干活了
     * @private
     */
    _lazyLoadHandler() {
      //找出哪些是已经完成工作了的
      console.log('_lazyLoadHandler');
      const freeList = []
      this.ListenerQueue.forEach((listener, index) => {
        if (!listener.state.error && listener.state.loaded) {
          return freeList.push(listener)
        }
        //判断是否在窗体内,不在就不去加载图片了
        if(!listener.checkInView())return;
        listener.load()
      })
      //把完成工作的listener剔除
      freeList.forEach(vm => remove(this.ListenerQueue, vm))
    }

listener.js:

 getRect() {
    this.rect = this.el.getBoundingClientRect()
  }

  checkInView() {
    this.getRect()
    return (this.rect.top < window.innerHeight && this.rect.bottom > 0
      && this.rect.left < window.innerWidth && this.rect.right > 0)
  }

我们修改一下Lazy.vue测试页面,给img一个定高,不然默认都加载了:

<div v-for="(image,index) in images" v-bind:key="'image-'+index">
      <img v-lazy="{src: image}" width="100%" height="500px">
    </div>

然后给LazyDelegate加一个log提示:

_lazyLoadHandler() {
     ..
        //判断是否在窗体内,不在就不去加载图片了
        if(!listener.checkInView())return;
        console.log(listener.src+'可以加载了');
        listener.load()
      })
     ...
    }

我们跑一下代码看一下效果:

2.gif

我们可以看到log,当我们滑动的时候当快滑动到某个img的时候,我们才去加载当前img,我们对比一下流量消耗:
屏幕快照 2018-08-08 下午6.36.14.png

可以看到,效果还是很明显的第一屏的时候只有739kb了,哈哈.其实也没有啥牛逼的东西,只是换了种加载模式而已,我们之前是以空间换时间,现在变成了以时间换空间, 很明显,第二种是比较符合移动端策略的.

有童鞋会说了,你既然是框架,为啥还把滚动的监听放在组件中呢? 还有,你怎么能确定别人是body在滚动呢? 也可以是某个模块自己在滚动啊,这样不就jj了? 是的!! 我们来优化一下我们的代码,当我们的指令执行到add的时候,我们创建监听者.
那么除了监听我们的scroll事件外我们还要监听哪些事件呢? 我们列一下:

const DEFAULT_EVENTS = ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']

然后我们指令走add的时候获取滚动元素,加上监听:

 /**
     * 只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
     * @param el 指令所绑定的元素,可以用来直接操作 DOM 。
     * @param binding
     * @param vnode
     */
    add(el, binding, vnode) {
      console.log('add');
      let {src, loading, error} = this._valueFormatter(binding.value)

      Vue.nextTick(() => {
        const newListener = new LazyListener({
          el,
          loading,
          error,
          src,
          options: this.options,
          elRenderer: this._elRenderer.bind(this),
        })
        this.ListenerQueue.push(newListener)
        //获取滚动元素
        let $parent;
        if (!$parent) {
          $parent = scrollParent(el)
        }
        //window添加监听
        this._addListenerTarget(window)
        //给父滚动元素添加监听
        this._addListenerTarget($parent)
        Vue.nextTick(() => {
          this.lazyLoadHandler()
        })
      })
    }

    /**
     * 添加监听
     * @param el
     * @private
     */
    _addListenerTarget(el) {
      if (!el) return
      DEFAULT_EVENTS.forEach((evt) => {
        el.addEventListener(evt, this.lazyLoadHandler.bind(this), false)
      })

    }

function scrollParent(el) {
  if (!(el instanceof HTMLElement)) {
    return window
  }
  let parent = el

  while (parent) {
    if (parent === document.body || parent === document.documentElement) {
      break
    }

    if (!parent.parentNode) {
      break
    }

    if (/(scroll|auto)/.test(overflow(parent))) {
      return parent
    }

    parent = parent.parentNode
  }

  return window
}

function overflow(el) {
  return style(el, 'overflow') + style(el, 'overflow-y') + style(el, 'overflow-x')
}

const style = (el, prop) => {
  return typeof getComputedStyle !== 'undefined'
    ? getComputedStyle(el, null).getPropertyValue(prop)
    : el.style[prop]
}

最后我们修改下测试页面的代码:

<template>
  <div class="opt-container">
    <div v-for="(image,index) in images" v-bind:key="'image-'+index">
      <img v-lazy="{src: image}" width="100%" height="500px">
    </div>
  </div>
</template>

<script>
  const IMAGES = [
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=c136f7387cfe2b79161f2f93bff6cb96&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F09%2F65%2Fb3468db29cb1.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=de941561df3b6fd53b2df9bfd6c0b187&imgtype=0&src=http%3A%2F%2Fpic43.photophoto.cn%2F20170413%2F0008118236659168_b.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283185&di=aff7e8aa60813f6e36ebc6f6a961255c&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d60f57e8a07d0000018c1bfa2564.JPG%403000w_1l_2o_100sh.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533726597165&di=198b9836a377021082281fcf0e5f3331&imgtype=0&src=http%3A%2F%2Fchongqing.sinaimg.cn%2Fiframe%2F159%2F2012%2F0531%2FU9278P1197T159D1F3057DT20140627094648.jpg',
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533726597167&di=e06fc5f74fac9bb61d229249219cbe4f&imgtype=0&src=http%3A%2F%2Fimg2.ph.126.net%2FuWKrNCkdBNBPzdjxCcUl-w%3D%3D%2F6630220042234317764.jpg'
  ]
  export default {
    name: 'Lazy',
    data() {
      return {
        images: IMAGES,
        showImage: true
      }
    },
    mounted(){
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .opt-container {
    font-size: 0px;
  }
</style>

然后我们运行代码:
2.gif

当我们往上滑动的时候,跟我们之前的效果一致了~~~

好啦!! 到这里我们图片框架代码都已经解析完毕了,也带着一起敲了一遍,有童鞋会觉得代码有点熟悉哈,没错,就是vue-lazyload的代码,哈哈!! 小伙伴不要把我代码直接拖进工程哈,要用的话直接去拖vue-lazyload的代码,最后附上demo的github链接,以及vue-lazyload的github链接:

DEMO地址: https://github.com/913453448/VuexDemo.git

[Vue-Lazyload地址:https://github.com/hilongjw/vue-lazyload
](https://github.com/hilongjw/vue-lazyload
)

最后,欢迎志同道合的小伙伴入群,欢迎交流~~~~
qq群号:

屏幕快照 2018-08-08 下午8.00.13.png

猜你喜欢

转载自blog.csdn.net/vv_bug/article/details/81673559