All files / src/mixins lazy.js

88.24% Statements 15/17
82.35% Branches 14/17
87.5% Functions 7/8
87.5% Lines 14/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84                      22x                                               51x         51x           152x 132x 132x 132x     20x   20x   6x     5x             51x       49x       52x                  
import { watchElementVisibility } from "../helpers/visibility"
import {
  LAZY_LOADING,
  CLD_IMAGE_WRAPPER_CLASS,
  IMAGE_CLASSES,
} from "../constants"
 
/**
 * If necessary watches for root elements visibility
 * and posts the result to components data
 */
export const lazy = {
  props: {
    /**
     * **Deprecated**
     * 
     * Whether to only load the asset when it needs to be displayed instead of when the page first loads.
     * @deprecated - Use `loading` instead
     */
    lazy: {
      type: Boolean,
      default: false
    },
 
    /**
     * Set loading type for the component
     * use loading='lazy' to lazyload
     */
    loading: {
      type: String,
      default: ''
    }
  },
 
  data() {
    return { visible: false };
  },
 
  computed: {
    hasLazyLoading() {
      return this.lazy || this.loading === LAZY_LOADING
    }
  },
 
  methods: {
    updateVisibilityObservation() {
      if (!this.hasLazyLoading) {
        this.visible = true
        this.cancelVisibilityListener && this.cancelVisibilityListener()
        return
      }
 
      const isElementRendered = !!this.$el && (this.$el.classList?.contains(IMAGE_CLASSES.DEFAULT) || this.$el.classList?.contains(CLD_IMAGE_WRAPPER_CLASS))
 
      if (!isElementRendered || this.cancelVisibilityListener) return
 
      this.cancelVisibilityListener = watchElementVisibility(
        this.$el,
        isVisible => {
          this.visible = this.visible || isVisible;
        }
      )
    }
  },
 
  created() {
    this.updateVisibilityObservation();
  },
 
  mounted() {
    this.updateVisibilityObservation();
  },
 
  updated() {
    this.updateVisibilityObservation();
  },
 
  destroyed() {
    if (this.cancelVisibilityListener) {
      this.cancelVisibilityListener();
    }
  }
};