You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在运行时动态加载Svelte模板?相关实现与性能疑问

Dynamic Component Loading & Slot Performance in Svelte

Great question—let’s break this down clearly, since you’re asking about two key parts of Svelte’s component model.

1. Loading Arbitrary Templates via fetch() & Injecting Data

Svelte’s <svelte:component> does default to expecting compile-time imports, but you absolutely can load components dynamically at runtime (including via fetch()), though there are a couple of approaches to consider:

Option 1: Lazy-Load Pre-Compiled Components

The most performant and common method is using dynamic import() (which leverages fetch() under the hood) to load pre-compiled Svelte components. You can inject data into them via props just like any regular component.

Here’s a practical example:

<script>
  let loadedComponents = [];
  const componentData = {
    profile1: { name: "Alex", bio: "Dynamic component loaded on user action" },
    profile2: { name: "Sam", bio: "Another fetched entry" }
  };

  async function loadComponent(componentName, dataKey) {
    // Dynamically import the component chunk
    const module = await import(`./components/${componentName}.svelte`);
    // Add the component and its data to our render list
    loadedComponents = [
      ...loadedComponents,
      { component: module.default, data: componentData[dataKey] }
    ];
  }
</script>

<button on:click={() => loadComponent('UserProfile', 'profile1')}>Load Profile 1</button>
<button on:click={() => loadComponent('UserProfile', 'profile2')}>Load Profile 2</button>

{#each loadedComponents as item}
  <svelte:component this={item.component} {...item.data} />
{/each}

Option 2: Loading Raw Svelte Templates (Advanced)

If you need to fetch uncompiled Svelte template code (e.g., from a CMS or API), you’ll need to include the Svelte compiler in your client bundle (note: this increases bundle size). You can compile the fetched code at runtime and render it:

<script>
  import { compile } from 'svelte/compiler';

  let dynamicComponent = null;

  async function loadRawTemplate() {
    const response = await fetch('/api/get-custom-template');
    const templateCode = await response.text();

    // Compile the raw template into a usable component
    const { js } = compile(templateCode, { generate: 'dom' });
    const module = await import(`data:text/javascript,${js.code}`);
    dynamicComponent = module.default;
  }
</script>

<button on:click={loadRawTemplate}>Load Custom Template</button>

{#if dynamicComponent}
  <svelte:component this={dynamicComponent} injectedData="Hello from runtime!" />
{/if}

Keep in mind: client-side compilation adds overhead, so this is best for cases where templates change frequently and pre-compiling isn’t feasible.

2. Performance of <slot> for Content Updates

Short answer: <slot> is designed to be highly performant, and you shouldn’t run into issues in most scenarios.

Here’s why:

  • Svelte compiles slot content directly into the parent component’s render logic, so there’s no extra runtime overhead compared to rendering content inline.
  • When slot content updates, Svelte’s reactivity system only re-renders the specific parts that changed—no full component re-renders unless absolutely necessary.
  • Compared to passing HTML as strings (e.g., {@html someRawString}), slots are safer and more efficient because Svelte can optimize DOM updates precisely.

That said, if you’re working with extremely complex slot content that updates very frequently, you might see minor performance hits. In those cases, you can:

  • Split the slot content into smaller, focused child components to limit the scope of updates.
  • Use the {#key} block to force a full re-render of the slot content only when a specific value changes, instead of reacting to every tiny update.

内容的提问来源于stack exchange,提问作者Jared

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:26:10