0

It's a single line of code, I tried a lot of approaches, but I just can't get the result I want.

What do I want?

I want to set the attribute loading = lazy starting at the second item in the array. I tried a lot of things, my last temptation was to use the post ID. But does not work. Look at else if.

<script>
    // post props
    export let post;
</script>

<!--HTML here-->
<div>
    <!-- display posts images -->
    {#if post.image}
        <!--check if image is not empty -->
        <img src={post.image.formats.medium.url} alt={post.title} />
        <!-- if id is greater than 2 add loading="lazy" -->
    {:else if post.id > 2}
        <!-- set lazy images -->
        <img src={post.image.formats.medium.url} alt={post.title} loading="lazy" />
    {:else}
        <!-- if no images then placeholder -->
        <img src="images/900x600.png" alt={post.title} loading="lazy" />
    {/if}

1 Answer 1

2

If post.image is true, the else if will never be checked/executed. You could simplify this by always setting the loading attribute. Personally I find this easier to understand because you actually want to do the same thing for every element that has an image.

{#if post.image}
    <!--check if image is not empty -->
    <img src={post.image.formats.medium.url} alt={post.title} loading={post.id > 2 ? 'lazy' : 'eager'} />
{:else}
    <!-- if no images then placeholder -->
    <img src="images/900x600.png" alt={post.title} loading="lazy" />
{/if}
1
  • Thank you so much, Felix! I will use this approach from now on. Thanks! Commented Nov 23, 2021 at 13:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.