如何加载占位符图像然后在 HTTP 调用完成后切换到真实图像?

How to load a placeholder image then toggle to the real one once HTTP calls are done?

我目前正在做一个项目,页面上有一个特别大的 gif 文件。

我希望能够在加载 gif 以提高网站性能的同时加载更小的内容,例如静态图像或什至可能只是彩色图像 div。

目前的技术栈是Nuxt和SASS。

显然我需要添加一些示例代码。这是目前图像的渲染方式。

此外,为了进一步说明,我希望在加载此 gif 之前优先加载页面上的所有其他元素。

<img src="filename.gif" />

你可以用这个

<style>
   .wrapper {
     width: 30rem;
     height: 30rem;
     background-color: orangered;
   }
</style>
<div class="wrapper">
   <img src="filename.gif" />
</div>

假设我们有一个大的本地图像 tasty.jpg(巨大的 4k 比萨饼)和一个带鸭子的小图像,下面是如何在使用 fetch() 钩子时在两者之间进行简单的交换。

<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>