Created
October 21, 2021 14:31
-
-
Save OliverMax/b6ed483ed12b9b2893a34b08ef7cc7f7 to your computer and use it in GitHub Desktop.
load images with cache
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> | |
| <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