【问题标题】:Is there a way to defer the loading of dynamic imports in a Sapper route?有没有办法在 Sapper 路由中延迟加载动态导入?
【发布时间】: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


【解决方案1】:

每当调用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 bundler 中启用代码拆分,看起来你已经完成了。

【讨论】:

  • 这可行,但在 Chrome 中触发任何点击事件之前,服务工作者仍会拉取该模块以提供离线支持。作为一个有趣的旁注,Chrome 和 Firefox 在他们的网络面板中处理这个问题的方式不同,这在测试时一开始很混乱。触发点击事件时,Chrome 会显示服务工作请求和脚本请求。另一方面,Firefox 只显示点击事件的请求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
  • 2018-11-11
  • 2017-02-26
  • 2018-07-04
  • 2017-08-26
相关资源
最近更新 更多