0

I am using SvelteJs with svelte-spa-router.

I have my cases where I do

<script>
import Component1 from './Component1.svelte'
import Component2 from './Component2.svelte'
</script>

    {#if condition}
       <Component1 {...props1} />
    {:else}
       <Component2  {...props2} />
    {/if}

Is there a better way I can do this? Can I dynamically import and render components only when condition is met?

1 Answer 1

5

I think what you need to do is called "Lazy loading" which is loading the component only when it needs to be rendered.

This concept can be used in svelte, you only need the <svelte:component /> and import('') function

// Component.svelte
<div>
    Hello world
</div>

let's import that component dynamically

<script>
    export let props = {}
    export let condition = false
</script>

{#await import('./Component.svelte') then value }
    <svelte:component this={value.default} {...props} />
{/await}

let's add a condition

{#if condition}
  {#await import('./Component.svelte') then value }
        <svelte:component this={value.default} {...props} />
    {/await}
{/if}

Now the component will get imported only if the condition is met

you check this REPL

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly the solution I was about to post. Thank's for the help!
Is there a way to do this using svelte static adapter for build?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.