Skip to content

Instantly share code, notes, and snippets.

@OliverMax
Created October 21, 2021 14:31
Show Gist options
  • Save OliverMax/b6ed483ed12b9b2893a34b08ef7cc7f7 to your computer and use it in GitHub Desktop.
Save OliverMax/b6ed483ed12b9b2893a34b08ef7cc7f7 to your computer and use it in GitHub Desktop.
load images with cache
<template>
<picture data-vue-component-name="AppImage">
<source
v-if="webp"
:srcset="cachedImages[webp]"
type="image/webp"
>
<img
v-if="png"
:src="cachedImages[png]"
:alt="alt"
>
</picture>
</template>
<script setup>
import { reactive, watch } from 'vue';
import { request, excludeKeys, forEach } from '@xsys2/functions';
const props = defineProps({
webp: {
type: String,
default: null,
},
png: {
type: String,
default: null,
},
alt: {
type: String,
default: null,
},
});
const cachedImages = reactive({});
function isImageExistInCache(url) {
return Object.prototype.hasOwnProperty.call(props, url);
}
async function requestBlob(url) {
return request({ method: 'GET', url, responseType: 'blob' });
}
function convertBlobToImage(blob) {
return (window.URL || window.webkitURL).createObjectURL(blob);
}
function saveImageToCache(url, image) {
cachedImages[url] = image;
}
watch(
props,
(value) => {
forEach(excludeKeys(value, 'alt'), (_propName, url) => {
if (!isImageExistInCache(url)) {
requestBlob(url)
.then(convertBlobToImage)
.then(image => saveImageToCache(url, image));
}
});
},
{
immediate: true,
},
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment