Big front-end learning-server-side rendering study notes

Server-side rendering

Article content output source: big front-end high-paying training camp

I. Overview

1. Front-end framework based on client-side rendering

  • Angular
  • React
  • View

2. SPA single page application

advantage:

  • Good user experience
  • High development efficiency
  • Good rendering performance
  • Good maintainability

Disadvantages:

  • Long first screen rendering time
  • Not good for SEO

3. Learn from traditional server rendering

Insert picture description here

4. Client activation as SPA

Insert picture description here

5. Isomorphic applications

  • The first screen is rendered straight out through the server side, which solves the slow first screen rendering of SPA applications and is not conducive to SEO problems
  • Get a better user experience through client-side rendering of the result page content interaction
  • This method is usually called modern server-side rendering, also called isomorphic rendering
  • Applications built in this way are called server-side rendering applications or isomorphic applications

6. Related concepts

  • What is rendering: stitching data and templates together. The essence of rendering is the analysis and replacement of strings.
  • Traditional server-side rendering: early web page rendering was performed on the server-side
  • Client rendering
  • Modern server-side rendering (isomorphic rendering)

2. Traditional server rendering (SSR)

1. Case

Insert picture description here

index.js

const express = require('express')
const fs = require('fs')
const template = require('art-template')

const app = express()

app.get('/', (req, res) => {
    
    
  // 1. 获取页面模板
  const templateStr = fs.readFileSync('./index.html', 'utf-8')
  console.log(templateStr)
  // 2. 获取数据
  const data = JSON.parse(fs.readFileSync('./data.json', 'utf-8'))
  console.log(data)
  // 3. 渲染:数据 + 模板 = 最终结果
  const html = template.render(templateStr, data)
  console.log(html)
  // 4. 把渲染结果发送给客户端
  res.send(html)
})

app.listen(8081, () => {
    
    
  console.log('running......')
})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>传统的服务端渲染示例</title>
</head>
<body>
  <h1>
    传统的服务端渲染示例
  </h1>
  <h2>{
   
   {title}}</h2>
  <ul>
    {
   
   { each data }}
    <li>{
   
   {$value.name}}</li>
    {
   
   { /each }}
  </ul>
</body>
</html>

data.json

{
    
    
  "data": [
    {
    
    
      "id": 1,
      "name": "jal"
    },
    {
    
    
      "id": 2,
      "name": "wyb"
    }
  ],
  "title": "王一博0805生日快乐"
}

2. Disadvantages

  • The front-end and back-end code are completely coupled together, which is not conducive to development and maintenance
  • There is not enough room for the front end
  • Server pressure is high
  • Average user experience

Three, client rendering (CSR)

The previous shortcomings of server-side rendering have been effectively solved with the popularization of client-side Ajax technology. Ajax makes it possible for the client to dynamically obtain data. Therefore, the work of server-side rendering comes to the client.

Take the Vue.js project as an example to understand the client rendering process.

  • The backend is responsible for processing the data interface
  • The front end is responsible for rendering interface data to the page

The front end is more independent and no longer limited to the back end.

However, client-side rendering also has some obvious shortcomings:

  • The first screen rendering is slow: because the client rendering initiates at least three Http requests, the first time is to request the page, the second time is to request the JS script in the page, and the third time is to request dynamic data.

  • Not conducive to SEO: because the content rendered by the client is generated by JS, and the search engine will only request the html of the network path, and will not request the JS script in the html for parsing, so the search engine gets it The first screen is empty, and SEO for single-page applications is almost zero.

    // 搜索引擎是怎么获取网页内容的?
    const http = require('http')
    
    http.get('http://localhost:8080', res => {
          
          
      let data = ''
      res.on('data', chunk => {
          
          
        data += chunk
      })
      res.on('end', () => {
          
          
        console.log(data)
      })
    })
    
    /*
    打印结果:
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <link rel="icon" href="/favicon.ico">
        <title>vuex-cart-demo-template</title>
      <link href="/js/about.js" rel="prefetch"><link href="/js/app.js" rel="preload" as="script"><link href="/js/chunk-vendors.js" rel="preload" as="script"></head>
      <body>
        <noscript>
          <strong>We're sorry but vuex-cart-demo-template doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
        </noscript>
        <div id="app"></div>
        <!-- built files will be auto injected -->
      <script type="text/javascript" src="/js/chunk-vendors.js"></script><script type="text/javascript" src="/js/app.js"></script></body>
    </html>
    */
    

4. Modern server-side rendering (isomorphic rendering)

1. Isomorphic rendering = back-end rendering + front-end rendering

  • Based on frameworks such as React and Vue, the combination of client-side rendering and server-side rendering
    • Execute once on the client, and the user implements server-side rendering (straight out of the first screen)
    • Execute again on the client to take over page interaction
  • The core solves the problem of SEO and slow first screen rendering
  • It has the advantages of traditional server-side rendering as well as the advantages of client-side rendering.

2. How to achieve isomorphic rendering?

  • Official solutions using frameworks such as Vue and React
    • Advantages: help to understand the principle
    • Disadvantages: need to build an environment
  • Use third-party solutions
    • Next.js of React Ecosystem
    • Nuxt.js of Vue Ecosystem

3. Take Nuxt.js of the Vue ecosystem as an example to demonstrate isomorphic rendering applications

  1. Create a folder, and then enter the folder to execute the yarn initgenerated package manager

  2. Then perform the yarn add nuxtinstallation of Nuxt

  3. Add scripts command in package.json"dev": "nuxt"

  4. Create pages folder, create index.vue file and about.vue file in this folder, nuxt will automatically generate routing based on pages path.

    // index.vue
    <template>
      <div>
        <h1>首页</h1>
      </div>
    </template>
    
    <script>
    export default {
           
           
    
    }
    </script>
    
    <style scoped>
    
    </style>
    
    // about.vue
    <template>
      <div>
        <h1>About</h1>
      </div>
    </template>
    
    <script>
    export default {
           
           
    
    }
    </script>
    
    <style scoped>
    
    </style>
    
    
  5. Execute yarn devthis Nuxt project, open the localhost:3000 port, the default is pages/index.vue page, and then visit localhost:3000/about to access the pages/about.vue page

  6. asyncDataGet the json data in the pages/index.vue page through the method, and the static json data file is placed in the static directory. The hook function provided in Nuxt is asyncData()specifically used to obtain the data rendered by the server. Don't forget to install axios:yarn add axios

    // pages/index.vue
    <template>
      <div id="app">
        <h2>{
         
         { title }}</h2>
        <ul>
          <li
            v-for="item in data"
            :key="item.id"
          >{
         
         { item.name }}</li>
        </ul>
      </div>
    </template>
    
    <script>
    import axios from 'axios'
    
    export default {
           
           
      name: 'Home',
      components: {
           
           },
      // Nuxt中提供一个钩子函数`asyncData()`,专门用于获取服务端渲染的数据。
      async asyncData () {
           
           
        const {
           
            data } = await axios({
           
           
          method: 'GET',
          // 注意此处的URL要指定当前端口,否则默认会去服务端的80端口去查找。
          url: 'http://localhost:3000/data.json'
        })
        // 这里返回的数据会和data () {} 中的数据合并到一起给页面使用
        return data
      }
    }
    </script>
    
    <style scoped>
    
    </style>
    
    

    static/data.json

    {
          
          
      "data": [
        {
          
          
          "id": 1,
          "name": "jal"
        },
        {
          
          
          "id": 2,
          "name": "wyb"
        }
      ],
      "title": "王一博0805生日快乐"
    }
    
  7. A complete page is obtained in one request. Nuxt's server-side rendering solution solves the problem of slow first screen rendering and SEO problems

Insert picture description here

  1. Nuxt generates a SPA single-page application, which can be seen by adding routing navigation. The page is not refreshed when the Home and About components are switched. Create a folder layouts, and then create a default.vue file in this folder. The file name is a fixed requirement and cannot be taken at will

    <template>
    <div>
    <!-- 路由出口 -->
      <ul>
        <li>
          <!-- 类似于 router-link,用于单页面应用导航 -->
          <nuxt-link to="/">Home</nuxt-link>
        </li>
        <li>
          <!-- 类似于 router-link,用于单页面应用导航 -->
          <nuxt-link to="/about">About</nuxt-link>
        </li>
      </ul>
    <!-- 子页面出口 -->
      <nuxt />
    </div>
    </template>
    
    <script>
    export default {
           
           
    
    }
    </script>
    
    <style scoped>
    
    </style>
    
    

4. Issues with isomorphic rendering applications

  • Limited development conditions

    • Browser-specific code can only be used in certain lifecycle hook functions
    • Some external extension libraries may require special processing to run in server-side rendering applications
    • Cannot manipulate DOM during server rendering
    • Certain code operations need to distinguish the operating environment
  • More requirements involving build setup and deployment

    Client rendering Isomorphic rendering
    Construct Just build the client application Need to build two ends
    deploy Can be deployed in any web server Can only be deployed in Node.js Server
  • More server-side load

    • Rendering a complete application in Node requires a lot of CPU resources compared to only providing a static file server
    • If the application is used in a high-traffic environment, the corresponding server load needs to be prepared
    • Need more server-side rendering optimization work processing

5. Suggestions for server-side rendering

  • Does the first screen rendering speed really matter?
  • Do you really need SEO

Guess you like

Origin blog.csdn.net/jal517486222/article/details/107809945
Recommended