大型单页应用中的灵活网络数据预加载

Jul 29, 2024

Jul 29, 2024

By Mazzarolo Matteo

By Mazzarolo Matteo

Disclaimer: This post focuses on custom solutions to improve the performance of client-side rendered SPAs. If you’re using frameworks like Next.js, Remix, or similar, these optimizations are typically handled for you automatically :)

免责声明:本文侧重于改进客户端渲染的单页应用程序的自定义解决方案。如果您使用的是Next.js、Remix或类似的框架,这些优化通常会自动处理:)

In my experience with implementing client-side rendering, one important optimization is preloading network data on page load. From what I've seen in my last three companies, large SPAs typically require a series of network requests at page load. For example, to load user authentication data, environment configuration, etc.

根据我在实施客户端渲染方面的经验,一个重要的优化是在页面加载时预加载网络数据。根据我在过去三家公司的观察,大型单页应用通常需要在页面加载时进行一系列的网络请求。例如,加载用户身份验证数据、环境配置等。

When you start writing React applications, these network requests are usually initiated after the React app is mounted. And, while this approach does work, it can become inefficient as the application scales. Why wait for the app bundle to be downloaded, parsed, and for the React app to be loaded to start network requests when you know you can run them in parallel with these steps?

当您开始编写React应用程序时,这些网络请求通常在React应用程序挂载后发起。虽然这种方法确实有效,但随着应用程序规模的扩大,它可能变得低效。为什么要等待应用程序包被下载、解析并加载React应用程序后才开始网络请求,而您知道可以通过以下步骤并行运行它们呢?

Modern browsers offer tools like link rel="preload" and other resource hints to handle these specific use cases: they can be used to kickstart necessary network requests as soon as possible. However, these are mainly limited to simple, hardcoded requests. For more complex scenarios, you might need to rely on existing framework solutions or create a custom implementation.

现代浏览器提供了诸如link rel="preload"和其他资源提示等工具来处理这些特定用例:它们可以在尽可能早的时候启动必要的网络请求。然而,这些主要局限于简单的硬编码请求。对于更复杂的情况,您可能需要依赖现有的框架解决方案或创建自定义实现。

In cases where the only option is to build a custom solution, my preferred method involves injecting a small JavaScript script into the HTML document’s head to start network requests immediately. Unlike browser hints, this script is e...

开通本站会员,查看完整译文。

ホーム - Wiki
Copyright © 2011-2024 iteam. Current version is 2.139.0. UTC+08:00, 2024-12-28 09:30
浙ICP备14020137号-1 $お客様$