Fredrik Burmester
Fredrik Burmester

Reputation: 239

Is there a way to add the attribute loading="lazy" only in certain conditions?

I am using the relativly new HTML attribute loading="lazy". I only want it to be enabled when the number of images rendered on the page excedes 10. I am building my website using Vue.js v3. I am loading the images with a v-for card like this:

    <div
      class="gallery-panel"
      v-for="photo in filteredPhotos"
      v-bind:key="photo.id"
      :class="`${photo.display}`"
    >
      <a @click="this.$router.push(`/Album/${album}/Photo/${photo.id}`)">
        <img
          loading="auto"
          v-bind:src="thumbUrl(photo.filename, album)"
          v-bind:alt="`${photo.filename}`"
        />
      </a>
    </div>

Where filteredPhotos is an array with image information from a JSON file.

Is there a way to change the loading="auto" to loading="lazy" when the number of photos is going to be more than 10?

Upvotes: 0

Views: 78

Answers (2)

SMAKSS
SMAKSS

Reputation: 10520

Well, you can simply add an index attribute to your v-for to check whether the length of your array exceeding 10 or not (Since the index will begin from 0 you should set your condition to > 9). Then you can make your loading attribute conditional like this:

<img :loading="index > 9 ? 'lazy' : 'auto'" />

So your final code should be something like this:

<div class="gallery-panel" v-for="(photo, index) in filteredPhotos" v-bind:key="photo.id" :class="`${photo.display}`">
  <a @click="this.$router.push(`/Album/${album}/Photo/${photo.id}`)">
    <img :loading="index > 9 ? 'lazy' : 'auto'" v-bind:src="thumbUrl(photo.filename, album)" v-bind:alt="`${photo.filename}`" />
  </a>
</div>

Upvotes: 1

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5176

You can use index of v-for e.g

<div
  class="gallery-panel"
  v-for="(photo, index) in filteredPhotos"
  v-bind:key="photo.id"
  :class="`${photo.display}`"
>
  <a @click="this.$router.push(`/Album/${album}/Photo/${photo.id}`)">
    <img
      :loading="index > 9 ? 'lazy' : 'auto'"
      v-bind:src="thumbUrl(photo.filename, album)"
      v-bind:alt="`${photo.filename}`"
    />
  </a>
</div>

Upvotes: 1

Related Questions