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.

Revisions

  1. OliverMax created this gist Oct 21, 2021.
    69 changes: 69 additions & 0 deletions AppImage.vue
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    <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>