有没有办法延迟Sapper路线中动态导入的加载?

时间:2020-10-02 15:43:49

标签: svelte sapper svelte-component

我正在处理的项目的主页上有一个相当重的组件。它包含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}

enter image description here

我正在使用动态导入来将沉重的组件强制放入其文件中,以减小主页文件的大小。我希望动态导入也可以将加载推迟到满足条件为止,但事实并非如此。

我已经看到了几个如何在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

是否有一种方法可以在初始页面加载后获取组件,就像服务工作者包含预加载的路由一样?

1 个答案:

答案 0 :(得分:2)

无论何时调用import,模块都会被导入。由于import被称为onMount(),因此它将在组件安装时(而不是单击时)加载。

将您的import调用移至点击处理程序,仅在处理点击后才会加载:

<script>

    let Component;
    let optionSelected = false;

    const handleClick = async () => {
      const foo= await import("./../components/Foo.svelte");
      Component = foo.default;
      optionSelected = true;
    };

</script>

<button on:click|preventDefault={handleClick}>
    Option Button
</button>

{#if optionSelected}
    <svelte:component this="{Component}" />
{/if}

请记住,在您的javascript捆绑器中启用代码拆分功能。

enter image description here