Skip to content

Instantly share code, notes, and snippets.

@sagarkbhatt
Last active November 2, 2017 08:02
Show Gist options
  • Save sagarkbhatt/a165caa4041fa7f2a18b9c84cc04443a to your computer and use it in GitHub Desktop.
Save sagarkbhatt/a165caa4041fa7f2a18b9c84cc04443a to your computer and use it in GitHub Desktop.
Intersection-Observer
<template>
<img width="width" height="height" :alt=" alt ? alt : altDefault " :src="trans" :data-src="src" v-on:error="handleNotFound( $event )"/>
</template>
<script>
import '../lib/intersection-observer';
import { getCustomPath } from '../helper-functions/ramda-functions';
export default {
props: [ 'width', 'height', 'alt', 'src'],
mounted: function( ) {
const vm = this;
vm.createIoInstance();
vm.createObserver();
},
data() {
return {
io: '',
altDefault: 'image',
trans: getCustomPath(['global_variable'], trans_img ), // 1x1 transparent image
};
},
methods: {
/**
* Create instance of Intersection Observer
*/
createIoInstance: function( ) {
const vm = this;
vm.io = new IntersectionObserver( vm.onChange, {
rootMargin: '60px',
threshold: 0,
});
},
/**
* Add element for IO api
*/
createObserver: function( ) {
const vm = this;
vm.io.observe( vm.$el );
},
/**
* Function to be used by IO API
* Fires action when intersection happens
*
* @param {string} changes Element
*/
onChange: function( changes ) {
const vm = this;
changes.forEach(change => {
if ( change.isIntersecting ) {
change.target.src = change.target.dataset.src;
change.target.style.opacity = 0;
change.target.onload = function( ) {
change.target.style.opacity = 1;
};
// stop observing this element
vm.io.unobserve( change.target );
}
});
},
/**
* Display default image if given image gives 404 error
* Handle event if given URL return 404
* @param {object} event Element
*/
handleNotFound: function( event ) {
let imagePlaceHolder = getCustomPath(['global_variable'], default_img );
event.target.src = imagePlaceHolder;
},
/**
* Display image onload
* @param {object} event Element
*/
displayImg: function( event ) {
event.style.opacity = 1;
},
},
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment