超过页面加载时间阈值时的 SvelteKit 加载指示器

SvelteKit loading indicator when a page load time threshold is exceeded

我在一个主要是服务器端呈现页面的网站上使用 SvelteKit。 SvelteKit 上的客户端导航非常漂亮,而且非常活泼。但是,有时在路由load()函数中调用后端服务器时,由于数据库长尾延迟,响应不是即时的,可能需要几秒。

创建仅在加载时间不是即时的(小于 200 毫秒)时才显示的加载指示器的最佳方法是什么?我知道通用 navigating 模式,但我特别希望创建一个不会触发的加载指示器,除非页面加载不是即时的。

Sveltekit 有一个名为“navigating”的存储变量,它从字面上指示客户端是否在加载页面之间。来自 Sveltekit docs:

navigating is a readable store. When navigating starts, its value is { from, to }, where from and to both mirror the page store value. When navigating finishes, its value reverts to null.

请注意,如果您的页面是预呈现的,它应该是“即时”的,因此不会显示加载指示器。如果不是,只要您的内容被提取 and/or 呈现,这个“导航”变量就不会为 null。如果你愿意,你可以让“微调器”组件不显示任何东西......直到 200 毫秒后(使用 setTimout 计时器)......这听起来像你想要的。

这是我过去使用的包装器组件的示例实现(请原谅 tailwindcss 语法...我复制并粘贴了它)。您可以在 __layout.svelte 中自定义此想法,或使用此 {#if $navigating} 逻辑包装组件或整个“页面”:

<script>
// USE THIS:
import { navigating } from '$app/stores'
// Example spinner/loading component is visible (when $navigating != null):
import Spinner from '$lib/design/Spinner.svelte'
...
</script>

  <main class="py-4">
    <div class="pagePaddingMain flex-col">
      {#if title}
        <h1 class="text-4xl text-center text-cText pb-4 sm:text-5xl">{title}</h1>
      {/if}
      {#if $navigating} <!-- LOOK HERE -->
        <div class="m-8">
          <Spinner />
          <h1 class="ext-3xl text-center text-cText">Fetching {title}...</h1>
        </div>
      {:else}
        <slot />
      {/if}
    </div>
  </main>

就是这样。祝你好运!