讓我們更深入地了解伺服器端渲染 (SSR) 的概念以及它如何增強 Web 應用程式的使用者體驗。
伺服器端渲染的概念
當使用者造訪您的網站時,他們通常最初會收到裸 HTML,然後觸發載入其他資源,例如 JavaScript(例如 App.js)和 CSS(例如 style.css)。這種傳統方法通常稱為客戶端渲染,這意味著使用者必須等待這些資源下載並執行才能看到任何有意義的內容。這種延遲可能會導致用戶體驗不佳,尤其是對於連接速度或裝置較慢的用戶而言。
伺服器端渲染透過向使用者發送完全渲染的 HTML 頁面來回應其初始請求來解決此問題。此預先渲染的 HTML 包含完整的標記,可讓使用者立即查看內容,而無需等待 JavaScript 載入和執行。
SSR 的主要優點包括:
減少最大內容繪製 (LCP) 的時間:使用者可以更快地看到內容,因為伺服器發送完整的 HTML 文件。
改進的 SEO:搜尋引擎可以更有效地索引您的內容,因為內容可以輕鬆以 HTML 格式取得。
更好的初始使用者體驗:使用者可以更快地開始閱讀內容並與內容互動,從而提高參與率。
平衡績效指標
雖然 SSR 可以減少 LCP,但它可能會增加 與下一次繪製的交互作用 (INP) 的時間。這是頁面載入後使用者與頁面互動所需的時間。目標是確保當用戶決定與網站互動時(例如單擊按鈕),必要的 JavaScript 已在後台加載,從而使互動流暢且無縫。
SSR 的糟糕實作可能會導致使用者看到內容但無法與其交互,因為 JavaScript 尚未載入。這可能比等待整個頁面最初加載更令人沮喪。因此,持續監控和測量效能指標以確保 SSR 真正改善使用者體驗至關重要。
在 Vite 和 React.js 中設定 SSR
我們會將其分解為幾個步驟:
- 建立 ClientApp 元件
- 更新index.html
- 建立 ServerApp 元件
- 設定建置腳本
- 設定節點伺服器
1. 建立ClientApp組件
我們首先建立一個 ClientApp.jsx 文件,它將處理所有特定於瀏覽器的功能。
// ClientApp.jsx import { hydrateRoot } from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom'; import App from './App';
在這裡,我們從react-dom/client 導入HydraRoot,從react-router-dom 導入BrowserRouter,以及我們的主要App 元件。
// ClientApp.jsx // Hydrate the root element with our app hydrateRoot(document.getElementById('root'), <browserrouter> <app></app> </browserrouter> );
我們使用 HydroRoot 在客戶端渲染我們的應用程序,指定根元素並使用 BrowserRouter 包裝我們的應用程式。此設定可確保所有特定於瀏覽器的程式碼都保留在此處。
接下來,我們需要修改我們的App.jsx。
// App.jsx import React from 'react'; // Exporting the App component export default function App() { return ( <div> <h1 id="Welcome-to-My-SSR-React-App">Welcome to My SSR React App!</h1> </div> ); }
在這裡,為了演示目的,我們保持應用程式元件簡單。我們將其匯出,以便它可以在客戶端和伺服器環境中使用。
2.更新index.html
接下來,我們需要更新index.html以載入ClientApp.jsx而不是App.jsx,並添加解析令牌以拆分伺服器中的HTML文件,以便我們可以串流傳輸根div中的內容。
<meta charset="UTF-8"> <link rel="icon" type="image/svg+xml" href="./vite.svg"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vite + React + TS</title> <div id="root"><!--not rendered--></div> <script type="module" src="./src/ClientApp.jsx"></script>
3. 建立ServerApp元件
現在,讓我們建立一個 ServerApp.jsx 檔案來處理伺服器端渲染邏輯。
// ServerApp.jsx import { renderToPipeableStream } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom/server'; import App from './App'; // Export a function to render the app export default function render(url, opts) { // Create a stream for server-side rendering const stream = renderToPipeableStream( <staticrouter location="{url}"> <app></app> </staticrouter>, opts ); return stream; }
4. 設定建置腳本
我們需要更新 package.json 中的建置腳本來建置客戶端和伺服器套件。
{ "scripts": { "build:client": "tsc vite build --outDir ../dist/client", "build:server": "tsc vite build --outDir ../dist/server --ssr ServerApp.jsx", "build": "npm run build:client && npm run build:server", "start": "node server.js" }, "type": "module" }
在這裡,我們為客戶端和伺服器定義單獨的建置腳本。 build:client 腳本建立用戶端捆綁包,而 build:server 腳本使用 ServerApp.jsx 建置伺服器套件。建置腳本運行兩個建置步驟,啟動腳本使用 server.js(將在下一步中建立)運行伺服器。
∴ 如果您不使用 TypeScript,請從客戶端和伺服器版本中刪除 tsc。
5. 配置節點伺服器
最後,讓我們在 server.js 中設定我們的 Node 伺服器。
// server.js import express from 'express'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import renderApp from './dist/server/ServerApp.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const PORT = process.env.PORT || 3001; // Read the built HTML file const html = fs.readFileSync(path.resolve(__dirname, './dist/client/index.html')).toString(); const [head, tail] = html.split('<!--not rendered-->'); const app = express(); // Serve static assets app.use('/assets', express.static(path.resolve(__dirname, './dist/client/assets'))); // Handle all other routes with server-side rendering app.use((req, res) => { res.write(head); const stream = renderApp(req.url, { onShellReady() { stream.pipe(res); }, onShellError(err) { console.error(err); res.status(500).send('Internal Server Error'); }, onAllReady() { res.write(tail); res.end(); }, onError(err) { console.error(err); } }); }); app.listen(PORT, () => { console.log(`Listening on http://localhost:${PORT}`); });
In this file, we set up an Express server to handle static assets and server-side rendering. We read the built index.html file and split it into head and tail parts. When a request is made, we immediately send the head part, then pipe the stream from renderApp to the response, and finally send the tail part once the stream is complete.
By following these steps, we enable server-side rendering in our React application, providing a faster and more responsive user experience. The client receives a fully rendered page initially, and the JavaScript loads in the background, making the app interactive.
Conclusion
By implementing server-side rendering (SSR) in our React application, we can significantly improve the initial load time and provide a better user experience. The steps involved include creating separate components for client and server rendering, updating our build scripts, and configuring an Express server to handle SSR. This setup ensures that users receive a fully rendered HTML page on the first request, while JavaScript loads in the background, making the application interactive seamlessly. This approach not only enhances the perceived performance but also provides a robust foundation for building performant and scalable React applications.
以上是使用 Vite 和 React.js 進行伺服器端渲染 (SSR) 指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

10款趣味橫生的jQuery遊戲插件,讓您的網站更具吸引力,提升用戶粘性!雖然Flash仍然是開發休閒網頁遊戲的最佳軟件,但jQuery也能創造出令人驚喜的效果,雖然無法與純動作Flash遊戲媲美,但在某些情況下,您也能在瀏覽器中獲得意想不到的樂趣。 jQuery井字棋遊戲 遊戲編程的“Hello world”,現在有了jQuery版本。 源碼 jQuery瘋狂填詞遊戲 這是一個填空遊戲,由於不知道單詞的上下文,可能會產生一些古怪的結果。 源碼 jQuery掃雷遊戲

本教程演示瞭如何使用jQuery創建迷人的視差背景效果。 我們將構建一個帶有分層圖像的標題橫幅,從而創造出令人驚嘆的視覺深度。 更新的插件可與JQuery 1.6.4及更高版本一起使用。 下載

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

Matter.js是一個用JavaScript編寫的2D剛體物理引擎。此庫可以幫助您輕鬆地在瀏覽器中模擬2D物理。它提供了許多功能,例如創建剛體並為其分配質量、面積或密度等物理屬性的能力。您還可以模擬不同類型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流瀏覽器。此外,它也適用於移動設備,因為它可以檢測觸摸並具有響應能力。所有這些功能都使其值得您投入時間學習如何使用該引擎,因為這樣您就可以輕鬆創建基於物理的2D遊戲或模擬。在本教程中,我將介紹此庫的基礎知識,包括其安裝和用法,並提供一

本文演示瞭如何使用jQuery和ajax自動每5秒自動刷新DIV的內容。 該示例從RSS提要中獲取並顯示了最新的博客文章以及最後的刷新時間戳。 加載圖像是選擇


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 Linux新版
SublimeText3 Linux最新版

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),