Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically load a Svelte template at runtime?

Tags:

svelte

I have looked at the documentation for [<svelte:component>] (here), but that looks like I would have had to import all of the possible templates at compile time.

Is it possible in Svelte to load any number of arbitrary templates from something like a fetch() call based on a user action? Then inject data into it?

Would it be inefficient to use <slot> for something like this, if I plan on updating it after the initial load?

like image 831
Jared Avatar asked May 11 '18 20:05

Jared


People also ask

Is Svelte dynamic?

<svelte:component> is a special Svelte element that allows you to accomplish the dynamic rendering. You pass the component you want to render as the value for a prop called this to the special element, in addition to any other props you want the child component to have.

What is $$ in Svelte?

Svelte will generate the code to automatically update them whenever data they depend on is changed. Note: Svelte uses the $: JavaScript label statement syntax to mark reactive statements.

What does $: mean in Svelte?

3. $: marks a statement as reactive. Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the $: JS label syntax. Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed.

Does Svelte use handlebars?

Svelte was designed to compile the template at build time. I'd recommend using a template engine (like handlebars) for your use case. This of course limits the available syntax to handlebars, and you can't use svelte components inside a handlebar template.


1 Answers

It's technically possible to create a component from the source text — the REPL does it, for example — since the compiler doesn't care if it's running in Node or the browser. But it's definitely not recommended! (It would defeat the object of using Svelte, since the compiler is somewhat large.)

Instead, you can dynamically import the components themselves, if you're using Rollup (with experimentalDynamicImport and experimentalCodeSplitting) or webpack:

<button on:click="loadChatbox()">
  chat to a customer service representative
</button>

{#if ChatBox}
  <svelte:component this={ChatBox}/>
{/if}

<script>
  export default {
    methods: {
      async loadChatbox() {
        const { default: Chatbox } = await import('./Chatbox.html');
        this.set({ Chatbox });
      }
    }
  };
</script>
like image 125
Rich Harris Avatar answered Sep 22 '22 03:09

Rich Harris