如何在Nuxt中正确延迟加载图像?

问题描述 投票:0回答:1

是否可以在客户端同时使用 - ssr 和延迟加载图像。这是我的情况。我的标记是用 img[src] 渲染的,在我的 chrome 浏览器中,我按 ctrl+U 并可以看到所有图像都有 src 属性(seo 机器人会识别它们,我很高兴),但在客户端我需要有img[data-src] 用于延迟加载。如果我在服务器端有一个 data-src 属性,seo 机器人将找不到任何 src (按 ctrl + U 将证明这一点),但所有图像都将以延迟加载的方式显示......我应该过滤标记在客户端接收之前(实际上我知道如何在nuxt中实现它)。请提出解决问题的任何想法或方向?

vue.js nuxt.js lazy-loading server-side-rendering src
1个回答
1
投票

以下是如何实现以下目标:

  • 从 API 获取一些图像
  • 在移动视口上显示 1 个图像(< 1000px) represented by the red line
  • 如果您的视口更宽,则有 4 个图像(桌面视口)
  • loading="lazy"
    在这里做繁重的工作,它在 不太旧的浏览器上运行良好
  • 如果您从移动设备开始,打开网络选项卡,按名为
    6
    的图像进行过滤,您会发现,如果增加视口 > 1000px(静止滚动时延迟加载),您将收到一些网络请求
<template>
  <div>
    <pre>all the interesting images: {{ pokemon.sprites.other }}</pre>
    <div class="reference-breakpoint"></div>

    <p>Down below are all the remaining images ⬇️</p>
    <img :src="pokemon.sprites.other.dream_world.front_default" />
    <img
      class="hide-when-mobile"
      loading="lazy"
      :src="pokemon.sprites.other.home.front_default"
    />
    <img
      class="hide-when-mobile"
      loading="lazy"
      :src="pokemon.sprites.other.home.front_shiny"
    />
    <img
      class="hide-when-mobile"
      loading="lazy"
      :src="pokemon.sprites.other['official-artwork'].front_default"
    />
  </div>
</template>

<script>
export default {
  async asyncData({ $axios }) {
    const pokemon = await $axios.$get(
      'https://pokeapi.co/api/v2/pokemon/charizard'
    )
    return { pokemon }
  },
}
</script>

<style scoped>
img {
  display: block;
  height: 100vh;
  width: auto;
}
.reference-breakpoint {
  width: 1000px;
  height: 1rem;
  background-color: red;
}
@media (max-width: 1000px) {
  .hide-when-mobile {
    display: none;
  }
}
</style>

对这个不满意?这是一个 intersectionObserver 示例,有点复杂,但也更强大/灵活。

© www.soinside.com 2019 - 2024. All rights reserved.