性能
开箱即用,SvelteKit 做了很多工作来使你的应用尽可能高效:
¥Out of the box, SvelteKit does a lot of work to make your applications as performant as possible:
代码分割,这样只加载当前页面所需的代码
¥Code-splitting, so that only the code you need for the current page is loaded
资源预加载,以便防止 ‘waterfalls’(请求其他文件的文件)
¥Asset preloading, so that ‘waterfalls’ (of files requesting other files) are prevented
文件哈希,以便你的资源可以永久缓存
¥File hashing, so that your assets can be cached forever
请求合并,以便从单独的服务器
load
功能获取的数据被分组为单个 HTTP 请求¥Request coalescing, so that data fetched from separate server
load
functions is grouped into a single HTTP request并行加载,以便单独的通用
load
函数同时获取数据¥Parallel loading, so that separate universal
load
functions fetch data simultaneously数据内联,以便在服务器渲染期间使用
fetch
发出的请求可以在浏览器中重播,而无需发出新请求¥Data inlining, so that requests made with
fetch
during server rendering can be replayed in the browser without issuing a new request保守的失效,以便
load
函数仅在必要时重新运行¥Conservative invalidation, so that
load
functions are only re-run when necessary预渲染(如果需要,可以根据每个路由进行配置),以便可以立即提供没有动态数据的页面
¥Prerendering (configurable on a per-route basis, if necessary) so that pages without dynamic data can be served instantaneously
链接预加载,以便热切期待客户端导航的数据和代码要求
¥Link preloading, so that data and code requirements for a client-side navigation are eagerly anticipated
尽管如此,我们(目前)还不能消除所有导致速度缓慢的根源。为了获得最佳性能,你应该注意以下提示。
¥Nevertheless, we can’t (yet) eliminate all sources of slowness. To eke out maximum performance, you should be mindful of the following tips.
诊断问题(Diagnosing issues)
¥Diagnosing issues
Google 的 PageSpeed Insights 和(用于更高级的分析)WebPageTest 是了解已部署到互联网的网站的性能特性的绝佳方法。
¥Google’s PageSpeed Insights and (for more advanced analysis) WebPageTest are excellent ways to understand the performance characteristics of a site that is already deployed to the internet.
你的浏览器还包含有用的开发者工具,用于分析你的网站,无论是部署还是本地运行:
¥Your browser also includes useful developer tools for analysing your site, whether deployed or running locally:
Chrome - Lighthouse、网络 和 性能 devtools
¥Chrome - Lighthouse, Network, and Performance devtools
Edge - Lighthouse、网络 和 性能 devtools
¥Edge - Lighthouse, Network, and Performance devtools
-
¥Firefox - Network and Performance devtools
Safari - 增强网页性能
请注意,在 dev
模式下本地运行的站点将表现出与你的生产应用不同的行为,因此你应该在构建后在 preview 模式下进行性能测试。
¥Note that your site running locally in dev
mode will exhibit different behaviour than your production app, so you should do performance testing in preview mode after building.
仪器(Instrumenting)
¥Instrumenting
如果你在浏览器的网络选项卡中看到 API 调用花费了很长时间,并且想要了解原因,你可以考虑使用 OpenTelemetry 或 Server-Timing 标头 等工具来检测后端。
¥If you see in the network tab of your browser that an API call is taking a long time and you’d like to understand why, you may consider instrumenting your backend with a tool like OpenTelemetry or Server-Timing headers.
优化资源(Optimizing assets)
¥Optimizing assets
图片(Images)
¥Images
减小图片文件的大小通常是对网站性能影响最大的更改之一。Svelte 提供 @sveltejs/enhanced-img
包(详情请参阅 images 页面),以简化此操作。此外,Lighthouse 可用于识别最严重的违规者。
¥Reducing the size of image files is often one of the most impactful changes you can make to a site’s performance. Svelte provides the @sveltejs/enhanced-img
package, detailed on the images page, for making this easier. Additionally, Lighthouse is useful for identifying the worst offenders.
视频(Videos)
¥Videos
视频文件可能非常大,因此应格外小心以确保它们得到优化:
¥Video files can be very large, so extra care should be taken to ensure that they’re optimized:
使用 Handbrake 等工具压缩视频。考虑将视频转换为 Web 友好格式,例如
.webm
或.mp4
。¥Compress videos with tools such as Handbrake. Consider converting the videos to web-friendly formats such as
.webm
or.mp4
.你可以使用
preload="none"
位于折叠下方的 延迟加载视频(但请注意,当用户启动它时,这会减慢播放速度)。¥You can lazy-load videos located below the fold with
preload="none"
(though note that this will slow down playback when the user does initiate it).使用 FFmpeg 等工具从静音视频中剥离音轨。
¥Strip the audio track out of muted videos using a tool like FFmpeg.
字体(Fonts)
¥Fonts
SvelteKit 在用户访问页面时会自动预加载关键的 .js
和 .css
文件,但默认情况下不会预加载字体,因为这可能会导致下载不必要的文件(例如 CSS 引用但当前页面实际上未使用的字体粗细)。话虽如此,正确预加载字体可以对你的网站速度产生很大影响。在你的 handle
钩子中,你可以使用包含字体的 preload
过滤器调用 resolve
。
¥SvelteKit automatically preloads critical .js
and .css
files when the user visits a page, but it does not preload fonts by default, since this may cause unnecessary files (such as font weights that are referenced by your CSS but not actually used on the current page) to be downloaded. Having said that, preloading fonts correctly can make a big difference to how fast your site feels. In your handle
hook, you can call resolve
with a preload
filter that includes your fonts.
你可以通过 subsetting 字体来减小字体文件的大小。
¥You can reduce the size of font files by subsetting your fonts.
减少代码大小(Reducing code size)
¥Reducing code size
Svelte 版本(Svelte version)
¥Svelte version
我们建议运行最新版本的 Svelte。Svelte 5 比 Svelte 4 更小更快,而 Svelte 4 又比 Svelte 3 更小更快。
¥We recommend running the latest version of Svelte. Svelte 5 is smaller and faster than Svelte 4, which is smaller and faster than Svelte 3.
包(Packages)
¥Packages
rollup-plugin-visualizer
有助于识别哪些包对你网站的大小贡献最大。你还可以通过手动检查构建输出(在 Vite 配置 中使用 build: { minify: false }
使输出可读,但请记住在部署应用之前撤消该操作)或通过浏览器的 devtools 的网络选项卡来找到删除代码的机会。
¥rollup-plugin-visualizer
can be helpful for identifying which packages are contributing the most to the size of your site. You may also find opportunities to remove code by manually inspecting the build output (use build: { minify: false }
in your Vite config to make the output readable, but remember to undo that before deploying your app), or via the network tab of your browser’s devtools.
外部脚本(External scripts)
¥External scripts
尝试尽量减少浏览器中运行的第三方脚本的数量。例如,不要使用基于 JavaScript 的分析,而要考虑使用服务器端实现,例如许多带有 SvelteKit 适配器的平台提供的实现,包括 Cloudflare、Netlify 和 Vercel。
¥Try to minimize the number of third-party scripts running in the browser. For example, instead of using JavaScript-based analytics consider using server-side implementations, such as those offered by many platforms with SvelteKit adapters including Cloudflare, Netlify, and Vercel.
要在 Web 工作器中运行第三方脚本(避免阻塞主线程),请使用 Partytown 的 SvelteKit 集成。
¥To run third party scripts in a web worker (which avoids blocking the main thread), use Partytown’s SvelteKit integration.
选择性加载(Selective loading)
¥Selective loading
使用静态 import
声明导入的代码将自动与页面的其余部分打包在一起。如果有一段代码仅在满足某些条件时才需要,请使用动态 import(...)
表单有选择地延迟加载组件。
¥Code imported with static import
declarations will be automatically bundled with the rest of your page. If there is a piece of code you need only when some condition is met, use the dynamic import(...)
form to selectively lazy-load the component.
导航(Navigation)
¥Navigation
预加载(Preloading)
¥Preloading
你可以使用 链接选项 预先加载必要的代码和数据,从而加快客户端导航速度。当你创建新的 SvelteKit 应用时,默认情况下会在 <body>
元素上配置此功能。
¥You can speed up client-side navigations by eagerly preloading the necessary code and data, using link options. This is configured by default on the <body>
element when you create a new SvelteKit app.
非必要数据(Non-essential data)
¥Non-essential data
对于加载缓慢且不需要立即使用的数据,从 load
函数返回的对象可以包含 promise 而不是数据本身。对于服务器 load
函数,这将导致数据在导航(或初始页面加载)后进入 stream。
¥For slow-loading data that isn’t needed immediately, the object returned from your load
function can contain promises rather than the data itself. For server load
functions, this will cause the data to stream in after the navigation (or initial page load).
防止瀑布(Preventing waterfalls)
¥Preventing waterfalls
最大的性能杀手之一是所谓的瀑布,即按顺序发出的一系列请求。这可能发生在服务器上或浏览器中。
¥One of the biggest performance killers is what is referred to as a waterfall, which is a series of requests that is made sequentially. This can happen on the server or in the browser.
当你的 HTML 请求 JS,而 JS 又请求 CSS,而 CSS 又请求背景图片和 Web 字体时,浏览器中可能会出现资源瀑布。SvelteKit 将通过添加
modulepreload
标签或标题在很大程度上为你解决此类问题,但你应该查看 devtools 中的网络选项卡 以检查是否需要预加载其他资源。如果你使用 Web fonts,请特别注意这一点,因为它们需要手动处理。¥Asset waterfalls can occur in the browser when your HTML requests JS which requests CSS which requests a background image and web font. SvelteKit will largely solve this class of problems for you by adding
modulepreload
tags or headers, but you should view the network tab in your devtools to check whether additional resources need to be preloaded. Pay special attention to this if you use web fonts since they need to be handled manually.如果通用
load
函数进行 API 调用以获取当前用户,然后使用该响应中的详细信息来获取已保存项目的列表,然后使用该响应来获取每个项目的详细信息,则浏览器最终将发出多个连续请求。这对性能来说是致命的,尤其是对于物理位置远离后端的用户。尽可能使用 服务器load
函数 来避免此问题。¥If a universal
load
function makes an API call to fetch the current user, then uses the details from that response to fetch a list of saved items, and then uses that response to fetch the details for each item, the browser will end up making multiple sequential requests. This is deadly for performance, especially for users that are physically located far from your backend. Avoid this issue by using serverload
functions where possible.服务器
load
函数也不能免受瀑布的影响(尽管它们的成本要低得多,因为它们很少涉及具有高延迟的往返)。例如,如果你查询数据库以获取当前用户,然后使用该数据对已保存项目列表进行第二次查询,则通常使用数据库连接发出单个查询会更有效。¥Server
load
functions are also not immune to waterfalls (though they are much less costly since they rarely involve roundtrips with high latency). For example if you query a database to get the current user and then use that data to make a second query for a list of saved items, it will typically be more performant to issue a single query with a database join.
托管(Hosting)
¥Hosting
你的前端应与后端位于同一数据中心,以最大限度地减少延迟。对于没有中央后端的站点,许多 SvelteKit 适配器支持部署到边缘,这意味着从附近的服务器处理每个用户的请求。这可以显著减少加载时间。某些适配器甚至支持 按路由配置部署。你还应该考虑从 CDN(通常是边缘网络)提供图片 - 许多 SvelteKit 适配器的主机将自动执行此操作。
¥Your frontend should be located in the same data center as your backend to minimize latency. For sites with no central backend, many SvelteKit adapters support deploying to the edge, which means handling each user’s requests from a nearby server. This can reduce load times significantly. Some adapters even support configuring deployment on a per-route basis. You should also consider serving images from a CDN (which are typically edge networks) — the hosts for many SvelteKit adapters will do this automatically.
确保你的主机使用 HTTP/2 或更新版本。Vite 的代码拆分会创建大量小文件以提高可缓存性,从而实现出色的性能,但这确实假设你的文件可以与 HTTP/2 并行加载。
¥Ensure your host uses HTTP/2 or newer. Vite’s code splitting creates numerous small files for improved cacheability, which results in excellent performance, but this does assume that your files can be loaded in parallel with HTTP/2.
进一步阅读(Further reading)
¥Further reading
在大多数情况下,构建高性能 SvelteKit 应用与构建任何高性能 Web 应用相同。你应该能够将来自通用性能资源(如 核心 Web 要素)的信息应用于你构建的任何 Web 体验。
¥For the most part, building a performant SvelteKit app is the same as building any performant web app. You should be able to apply information from general performance resources such as Core Web Vitals to any web experience you build.