Search code examples
server-side-renderingnuxt3.js

Is there any way to listen load event in nuxt 3 ssr?


When I used Nuxt 3 without ssr, images used to fire load event. But after switching to ssr server they doesn't.

Can I watch image loading status another way? I need to know if images loaded to hide preloader and show content for user.


Solution

  • Here is an example of AppImg component:

    <template>
      <client-only>
        <img
          v-bind="$attrs"
          @error="setFallback"
          @load="onLoad"
        />
    
        <template #fallback>
          <img key="ssr" v-bind="$attrs" />
        </template>
      </client-only>
    </template>
    

    Wrap your image inside <client-only> component.

    You might think that images will be missing on SSR, that's why you also need a #fallback slot to render an alternative image tag from server side.

    Because they are the same element (img) on client side and server side, you also need to add a key key="ssr" to one of those elements. Be careful in case you have a v-for on this component.

    And it work!