'How to load a placeholder image then toggle to the real one once HTTP calls are done?
I'm currently working on a project with a particularly large gif file on the page.
I'd like to be able to load something much smaller, like a static image or perhaps even just a colored div, while the gif is loading to improve the performance of the website.
The current tech stack is Nuxt and SASS.
Apparently I need to add some example code. Here is how the image is rendered at the moment.
Also, to add some further clarity, I am looking to prioritize the loading of all other elements on the page before this gif.
<img src="filename.gif" />
Solution 1:[1]
Assume we have a big local image tasty.jpg
(huge 4k pizza) and a small one with ducks, here is how to make a simple swap between both while using the fetch()
hook.
<template>
<div>
<img
:src="require(`~/assets/img/${currentImage}`)"
width="800"
height="800"
/>
</div>
</template>
<script>
export default {
async fetch() {
await this.$axios.$get('https://jsonplaceholder.typicode.com/photos')
console.log('5000 photos loaded!')
},
fetchOnServer: false, // the `fetch` hook will be called only client-side
computed: {
currentImage() {
if (process.server) return 'duck.jpg'
return this.$fetchState.pending ? 'duck.jpg' : 'tasty.jpg'
},
},
}
</script>
Solution 2:[2]
you can use this
<style>
.wrapper {
width: 30rem;
height: 30rem;
background-color: orangered;
}
</style>
<div class="wrapper">
<img src="filename.gif" />
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kissu |
Solution 2 | Mubasher Ali |