什么是 SPA
What is a SPA
一句话:单页应用 ——只加载一个 HTML, 之后的页面切换由 JS 在前端换内容, 不再向服务器请求整页。
好处:切页面没有白屏刷新、体验接近原生 App、 前后端彻底分离(后端只给 JSON)。
代价(面试重点问这半边):
- 首屏慢—— 要先下载并执行一大包 JS 才能看到内容。 解法是代码分割(
React.lazy,见 #347) 和 SSR。 - SEO 差—— 爬虫拿到的 HTML 是空的
<div id="root"></div>。 解法是 SSR / SSG(Next.js)。 - 路由要自己管—— 前进后退、深链接、刷新后还在当前页, 都得靠
historyAPI 和服务端的 fallback 配置。「刷新 404」就是漏配了 fallback。 - 内存泄漏风险—— 页面不刷新, 定时器和监听器不会被自动清掉。这就是
useEffect必须写清理函数的现实原因。
会追问:「MPA 什么时候更好?」—— 内容型站点(博客、文档、电商详情页), 重 SEO、首屏优先、交互不复杂的。答得出「看场景」比一味夸 SPA 好。
In one line: a single-page application — one HTML document gets loaded, and from then on JS swaps the content on the client instead of asking the server for a whole new page.
Upsides: no white flash when you change pages, it feels close to a native app, and front end and back end are fully separated (the server only returns JSON).
Costs — this is the half they probe:
- Slow first paint — you have to download and run a big JS bundle before anything shows up. The fixes are code splitting (
React.lazy, see #347) and SSR. - Weak SEO — a crawler receives an empty
<div id="root"></div>. The fix is SSR / SSG (Next.js). - You own the routing — back and forward, deep links, staying on the current page after a refresh, all of it rides on the
historyAPI plus a fallback on the server. “404 on refresh” means the fallback is missing. - Memory leaks — the page never reloads, so timers and listeners are never cleared for you. That is the practical reason
useEffectneeds a cleanup function.
Follow-up: “When is an MPA better?” — content sites (blogs, docs, product detail pages) where SEO and first paint matter and the interaction stays simple. “It depends on the case” beats praising SPAs unconditionally.