History of front-end page rendering
Server side rendering
The page is directly returned to the browser by the server, the route is the server route, the CHANGE of URL will refresh the page, the principle is similar to ASP, PHP and other traditional backend framework.
Client Side Rendering (CSR)
The Page is rendered after the JavaScript, CSS and other resource files are loaded, and routed to the client side, which is often referred to as SPA (Single Page Application).
Isomorphism (SSR)
The JavaScript code written can run in both browser and Node.js environment, and the server side rendering is used to improve the loading speed of the first screen. The routing after the first screen is controlled by the client, that is, the whole application is still a SPA after the user reaches the first screen.
After making clear the specific meaning of these three rendering schemes, we can find that both client side rendering and server side rendering have their obvious defects, and isomorphism is obviously a better solution combining the advantages of the two.
Advantages and disadvantages of CSR and SSR
Rendering mode | advantages | disadvantages |
---|---|---|
CSR | Network transmission of small amount of data, reduce server pressure, front and back end separation, local refresh, no need to request a complete page each time, good interaction can achieve a variety of effects | Not conducive to SEO, crawler can not see the complete program source code, the first screen rendering is slow |
SSR | Quick first screen rendering, SEO benefit, cache fragment generation, static file generation, energy saving (compared to the power consumption of client rendering) | Poor user experience and difficult maintenance |
Main factors in using SSR technology
- TTFP (Time To First Page) takes a long Time in A CSR project. Refer To the previous legend. In the rendering process of A CSR Page, the HTML file must be loaded First, and then the JavaScript file required for the Page must be downloaded. The JavaScript file is then rendered to generate the page. There are at least two HTTP request cycles involved in this rendering process, so it can take some time, which is why when you visit a regular React or Vue application on a low network speed, the initial screen will appear blank.
- The SEO capability of CSR projects is extremely weak, and it is almost impossible to get a good ranking in search engines. At present, most search engines mainly recognize the content of HTML, JavaScript file content recognition is still relatively weak. If a project’s traffic entry comes from a search engine, then using CSR for development is not appropriate.
Architecture diagram for enabling SSR technology
Why did SSR appear
In SSR projects, the React code is executed on both the client and server sides. As you might imagine, this isn’t a problem since it’s all JavaScript code that can be executed in Node or in a browser. But if your code manipulates the DOM, you have a problem. Node doesn’t have a DOM.
However, React introduces the concept of the virtual DOM. The virtual DOM is a JavaScript object of the real DOM. When React does page operations, it does not actually operate on the real DOM. On the server, I can manipulate JavaScript objects, determine if the environment is the server environment, and we convert the virtual DOM to a string output; On the client side, it can also determine the client environment and directly convert the virtual DOM into the real DOM to complete the page rendering.
How to use SSR technology
Since the SSR code is different from the CSR code, we create a new webpack.server.js file and modify the React code.
-
If you already have an Express server, it looks like this:
var express = require('express'); var app = express(); app.get('/', (req, res)=>{ res.send(`
Hello Wrold`) }) app.listen(8569) Copy the code -
Start the code and open localhost:8569 to see Hello word displayed on the page
-
Modify the Webpack and React code
LibraryTarget configures how to expose the Library. Umd means exposing your library to work under all module definitions. It will run in CommonJS, AMD environments, or export modules to variables under Global.
// webpack. module.exports = {mode: 'production'.entry: './src/module/demo.js'.output: { filename: 'demo-server.js'.path: path.join(__dirname, 'dist'), libraryTarget: 'umd'},... }Copy the code
//react const React = require('react'); class Box extends React.Component{ render(){ return ( <div>This is a box</div>)}}module.exports = <Box /> Copy the code
-
Modify express code
Node has no Windows and needs hacks
if(typeof window= = ='undefined'){ global.window = {} } ... const SSR = require('.. /dist/demo-server.js'); const { renderToString } = require('react-dom/server'); app.get('/', (req, res)=>{ res.end(`... <body>${renderToString(SSR)} </body> ... `) }) app.listen(8569) Copy the code
-
Start the code, open localhost:8569, and you should see the following image.
- Done, a simple SSR has been implemented.
Style resolution and initial data loading
We all know that Node has no style resolution and no XMLHttpRequest. What should we do when doing SSR? We can deploy static servers with client-side code, add placeholders to the.html code, and make placeholder replacements on the server side. Thus, when the client accesses the page, we load the style through the outer chain and get the initial page data by inserting a JSON object.
External chain loading style part of the code
// Packaged HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo</title>
<link href="main.77f6fd9c.css" rel="stylesheet"></head>
<body>
<div id="root"><! -- html-placeholder --></div>
<script type="text/javascript" src="https://lib.baomitu.com/react/16.8.6/umd/react.development.js"></script><script type="text/javascript" src="https://lib.baomitu.com/react-dom/16.8.6/umd/react-dom.development.js"></script><script type="text/javascript" src="demo-server.js"></script></body>
</html>
Copy the code
// express
if(typeof window= = ='undefined'){
global.window = {}
}
const express = require('express');
const app = express();
const SSR = require('.. /dist/demo-server.js');
const { renderToString } = require('react-dom/server');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.join(__dirname, '.. /dist/demo.html'), 'utf-8');
app.use(express.static('.. /dist/'))
app.get('/', (req, res)=>{
let html = template.replace('<! -- html-placeholder -->', renderToString(SSR));
res.end(html)
})
app.listen(8569)
Copy the code
reference
- Review the isomorphism (SSR) principle in React
- How to play the webpack