Last active
November 12, 2019 19:40
-
-
Save daliborgogic/65ee77356e93eef971f4b6d79ba53fb8 to your computer and use it in GitHub Desktop.
Conditionaly load img based on current users download speed and users choice to save data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<img :src="srcImage" :loading="loading" :alt="alt"> | |
</template> | |
<script> | |
export default { | |
props: { | |
src: { | |
type: Object, | |
default: () => ({ | |
full: 'https://placehold.it/1024', // retina maybe 2x? | |
medium: 'https://placehold.it/512', | |
small: 'https://placehold.it/256' | |
}) | |
}, | |
// Native image lazy-loading for the web | |
loading: { | |
type: String, | |
default: 'auto' // auto | eager | lazy | |
}, | |
alt: { | |
type: String, | |
default: '' | |
} | |
}, | |
data: () => ({ | |
downlink: null, | |
saveData: false, | |
observer: null, | |
intersected: false | |
}), | |
computed: { | |
srcImage() { | |
// Effective bandwidth estimate | |
const estimate = this.downlink | |
let type | |
switch (true) { | |
case 4 <= estimate: | |
type = 'full' | |
break | |
case estimate >= 1.5 && estimate <= 3.99: | |
type = 'medium' | |
break | |
case 1.49 <= estimate: | |
type = 'small' | |
break | |
} | |
return this.intersected !== this.saveData | |
? this.src[type] | |
: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/B8AAusB9FD6Pn0AAAAASUVORK5CYII=' | |
} | |
}, | |
mounted () { | |
// https://wicg.github.io/netinfo/ | |
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection | |
this.connectionChange(connection) | |
if ('IntersectionObserver' in window && this.laoding === 'auto') { | |
this.observer = new IntersectionObserver(entry => { | |
if (entry[0].isIntersecting) { | |
this.intersected = true | |
this.observer.disconnect() | |
} | |
}) | |
this.observer.observe(this.$el) | |
} | |
else this.intersected = true | |
connection.addEventListener('change', this.connectionChange) | |
}, | |
methods: { | |
connectionChange (event) { | |
const { type } = event | |
if ('change' === type) { | |
this.downlink = event.target.downlink | |
this.saveData = event.target.saveData | |
} | |
else { | |
this.saveData = event.saveData | |
this.downlink = event.downlink | |
} | |
} | |
}, | |
beforeDestroy () { | |
navigator.connection.removeEventListener('change', this.change) | |
if ('IntersectionObserver' in window) | |
this.observer.disconnect() | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Keep an eye on https://www.chromestatus.com/feature/5407907378102272