Original: Front-End Adventure, “SSR, SSG, and CSR Explained: A Complete Guide to Front-End Rendering”
SSR, SSG, and CSR Explained: A Complete Guide to Front-End Rendering 2024-05-15 6,007 5-minute read
In the world of front-end development, we often encounter three rendering technologies: SSR (Server-Side Rendering), SSG (Static Site Generation), and CSR (Client-Side Rendering). Each has unique advantages and disadvantages and is suitable for different scenarios and requirements. Below, we will introduce these three technologies in detail and deepen our understanding through code examples.
I. CSR (Client-Side Rendering)
Introduction:
CSR (Client-Side Rendering) is the most common rendering method in front-end development. In this mode, the server is mainly responsible for providing a static HTML file, which may contain a basic HTML structure and JavaScript scripts, while the actual page rendering is performed entirely by the browser on the client. This means that the page content is generated dynamically in the user's browser.
Advantages:
- Fast response: Once the HTML file has loaded, the browser can begin rendering the page without waiting for the server to return a fully rendered result.
- Highly dynamic: Because page rendering takes place on the client, various dynamic interaction effects can be implemented conveniently.
- Simple front-end deployment: Only a static service is needed to deploy the front-end code, reducing deployment costs.
Disadvantages:
- Long initial-screen loading time: Because the entire JavaScript bundle must be loaded, the initial screen may take longer to load, especially for complex single-page applications (SPAs).
- Unfavorable for SEO: Search-engine crawlers may not parse page content generated dynamically by JavaScript very well, resulting in poorer SEO.
- Blank-screen time: While the JavaScript code is loading and executing, the user may see a blank page—the so-called “blank-screen time.”
Example (using React):
// Assume there is a React component
import React from 'react';
function MyComponent() {
const [message, setMessage] = React.useState('Hello, CSR!');
const handleClick = () => {
setMessage('Clicked!');
};
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
// Include React and the component's JavaScript file in the HTML file
// The browser loads and executes this JavaScript to render the page
II. SSR (Server-Side Rendering)
Introduction:
SSR (Server-Side Rendering) is a technique that completes page rendering on the server. In this mode, after receiving a client request, the server first generates a complete HTML page from the request data and template files, then sends that page directly to the client. The user can therefore see the completed content immediately without waiting for JavaScript to load and execute.
Advantages:
- Fast initial-screen loading: Because the server has already generated a complete HTML page, the client can display it directly without waiting for JavaScript to load and execute.
- SEO-friendly: Search-engine crawlers can parse the HTML page content generated by the server effectively, which benefits SEO.
- Suitable for complex pages: For pages containing large amounts of data or requiring complex calculations, SSR can handle the work more effectively and reduce the load on the client.
Disadvantages:
- Heavy server load: The server must render the page again for every request, which may place excessive pressure on the server.
- Development constraints: When writing Vue components for SSR, developers must consider the differences between server and client environments and cannot depend too heavily on the client environment.
- Difficult debugging: The SSR debugging process is relatively complex because logs and error information from both the server and the client must be considered.
Example (server-side rendering with React):
// Server-side code (Node.js)
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const MyComponent = require('./MyComponent').default; // Assume MyComponent is the React component defined above
// Render the component as an HTML string
const html = ReactDOMServer.renderToString(<MyComponent />);
// Send the HTML string to the client
// ... (HTTP server and response-sending code omitted here)
III. SSG (Static Site Generation)
Introduction:
SSG (Static Site Generation) is a technique that generates static HTML pages at build time. In this mode, developers write template and data files, then use build tools such as Hugo or Gatsby to convert those files into static HTML pages. These pages can be deployed directly to a server without requiring real-time rendering by the server.
Advantages:
- Outstanding performance: Because the pages are static, there is no need to wait for server rendering; the browser loads and displays them directly, providing excellent performance.
- High security: Because the server provides only static files, the risk of attack is reduced.
- Suitable for content-oriented websites: SSG is a good choice for content-oriented websites whose content is not updated frequently, such as blogs and documentation sites.
Disadvantages:
- Limited dynamism: Because the pages are static, complex dynamic interaction effects are difficult to implement.
- Long build times: Large sites may take a long time to build.
- Unsuitable for frequent updates: SSG may not suit websites whose data must be updated frequently, because every update requires rebuilding and redeploying the entire website.
Example (using the Nunjucks template engine): Template file (index.njk):
<!DOCTYPE html>
<html>
<head>
<title>My Static Site</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
Build script (Node.js):
const nunjucks = require('nunjucks');
const fs = require('fs');
// Configure the Nunjucks template engine
nunjucks.configure('views', { autoescape: true });
// Render the template
const res = nunjucks.render('index.njk', { message: 'Hello, SSG!' });
// Write the rendered result to an HTML file
fs.writeFileSync('dist/index.html', res);
// You can now deploy the generated `dist/index.html` to a server
Summary
CSR, SSR, and SSG each have advantages and disadvantages and are suitable for different scenarios and requirements. When choosing which technology to use, you need to weigh the trade-offs according to the project's specific requirements.
For example, choose CSR for scenarios that require rich interactions and real-time data; choose SSR when initial-screen loading speed and SEO need to be optimized; and choose SSG for content that is updated infrequently and requires high performance. Multiple technologies can also be combined to provide a better user experience and improve performance.
This article was published across multiple platforms with mdnice.