【发布时间】:2021-01-18 07:18:06
【问题描述】:
我正在处理的项目的主页上有一个相当重的组件。它包括 Three.js 库和几个实用程序,但仅在用户触发的操作发生时才显示。无需将其包含在初始下载中,因为它只会为初始加载增加不必要的权重并增加加载时间。
<script>
let optionSelected = false;
const imports = {
component: () => import('./components/Component.svelte'),
};
</script>
<button on:click|preventDefault={() => optionSelected = true}>
Option Button
</button>
{#if optionSelected}
{#await imports['component']() then module}
<svelte:component this="{module.default}" />
{/await}
{/if}
我正在使用动态导入来强制将繁重的组件放入其文件中以减小主页文件的大小。我希望动态导入也会推迟加载,直到满足条件,但事实并非如此。
我已经看到了几个示例,说明如何在 onMount 生命周期函数中包含动态导入以绕过 SSR,但这并没有产生预期的结果。在需要之前,该组件仍包含在初始有效负载中。
<script>
import { onMount } from 'svelte';
let Component;
let optionSelected = false;
onMount(async () => {
const comp = await import('./../components/Component.svelte');
Component = comp.default;
});
</script>
<button on:click|preventDefault={() => optionSelected = true}>
Option Button
</button>
{#if optionSelected}
<svelte:component this="{Component}" />
{/if}
Sapper/Svelte possible to conditionally import components?
Making a component SSR compatible
有没有办法在初始页面加载后获取组件,类似于如何将预加载的路由包含在 service worker 中?
【问题讨论】:
-
您发现下面的解决方案对您有用吗?
标签: svelte sapper svelte-component