Ricardo de Paula
Ricardo de Paula

Reputation: 632

I can't find a way to make my code work in Svelte. The code involves an array of objects

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}

Upvotes: 0

Views: 87

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

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}

Upvotes: 2

Related Questions