What are server rendering (SSR), client rendering

What are server rendering and client rendering

1, Introduction

1.1 server side rendering (SSR)

sketch:
                           .
     when you right-click to view the source code, the page code can be seen in the source code.
     performance consumption is on the server side. When the user reaches a certain level, the backend will consider caching
      part of the data to avoid consuming too much resources for repeated rendering.
advantage:
     the front end takes less time, the first rendering is fast, and the content arrival time is faster
     beneficial to SEO
Disadvantages:
     the network transmits a large amount of data and occupies some server computing resources
     poor user experience
                     8195

1.2 client rendering

sketch:
      also known as front-end rendering, originated from the rise of js. ajax makes front-end rendering more mature
     the front end focuses on ui and the back end focuses on logic, which truly realizes the separation of front and back ends
     interact through the agreed API. The back end provides data, and the front end generates DOM according to the data and inserts it into the HTML page.
      most of the first rendering is to replace the data tag {}} in the original html
     right click to view the source code. The page code cannot be seen in the source code
     performance consumption on the client
advantage:
     reduce server pressure
      local refresh can be realized without requesting a complete page every time, and the experience is better
Disadvantages:
     the front end takes a lot of time, and the first screen rendering is slow. Before rendering, you need to download a pile of js and css files
     not conducive to SEO, and the crawler can't see the complete code
Difficulties:
      after data change, how can page response change save resources? Direct DOM reading and writing is very slow

2, What is client-side rendering

2.1 generate a vue project

We use vite tool to quickly generate a vue project, https://cn.vitejs.dev/

npm init @vitejs/app client-vue-app --template vue

2.2 installation and startup

cd vue-app
npm install (or `yarn`)
npm run dev (or `yarn dev`)

2.3 browser viewing effect

2.4 viewing source code

**Conclusion: * * by looking at the source code, we find that the source code does not display the actual rendered content in our page. We only see a main js file and a root element with id app, so we know that web content is rendered dynamically through js. js runs in the browser, which is the client. This way of rendering web content dominated by browser js is called client-side rendering

3, Server rendering

3.1 generate a node project

npm init -y

3.2 installing express

Official documents

npm install express --save

3.3 rendering small cases on the server side

app.js

const express = require('express')
const app= express()
// When the path is the following path, the complete html fragment is returned
app.get('/',(req,res) => res.send(`
  <html>
  <body>
  <h1> hello word </h1>
  </body>
  </html>
`))
app.listen(3000, ()=>{
  console.log('Please visit http://127.0.0.1:3000')
})

3.4 check the effect of operation

node app.js

3.5 open browser

http://127.0.0.1:3000

3.6 right click to view the source code

Summary: the so-called server-side rendering value is that the content of the page is completely determined by the server-side

4, Client side rendering VS server side rendering

Client side rendering is called CSR rendering, and server side rendering is called SSR rendering

4.1 comparison of operation architecture

explain

CSR execution process: the browser loads the html file - > the browser downloads the js file - > the browser runs vue code - > renders the page. SSR execution process: the browser loads the html file - > the server loads the content - > returns to the browser for rendering

4.2 comparison of development modes

Communication between front and back ends through JSON

SSR: the division of labor between the front end and the back end is complex. The front end needs to write an html template and give it to the back end, and the back end fills in the template content and returns it to the browser

4.3 summary of characteristics and advantages

Client (CSR)Server side rendering (SSR)
First render timelongVery short
seo supportdifferencegood
Development efficiency of front and rear end division of laborfastslow

5, Server-side rendering in vue framework

vue ssr basic usage

5.1 create a Vue SSR folder

vue-ssr

5.2 copy the files in the server folder

5.3 necessary for installation

npm install vue vue-server-renderer --save

5.4 vue server rendering minimum demo

app.js

const Vue = require('vue')
const express = require('express')
const renderer = require('vue-server-renderer').createRenderer()
const app= express()
// When the path is the following path, the complete html fragment is returned
// app.get('/',(req,res) => res.send(`
//   <html>
//   <body>
//   <h1> hello word </h1>
//   </body>
//   </html>
// `))

app.get('*',(req,res)=>{
  const apps = new Vue({
    data:{
      url:req.url
    },
    template:`<div>Visited URL yes:{{url}}</div>`
  })
  renderer.renderToString(apps,(err,html)=>{
    if(err) throw err
    res.send(html)
  })
})
app.listen(3000, ()=>{
  console.log('Please visit http://127.0.0.1:3000')
})

5.5 browser access

http://127.0.0.1:3000

5.6 viewing source code

5.7 problems

Modify app JS, add a button element and bind the click event in the way of vue

const Vue = require('vue')
const express = require('express')
const renderer = require('vue-server-renderer').createRenderer()
const app= express()
// When the path is the following path, the complete html fragment is returned
// app.get('/',(req,res) => res.send(`
//   <html>
//   <body>
//   <h1> hello word </h1>
//   </body>
//   </html>
// `))

app.get('*',(req,res)=>{
  const apps = new Vue({
    data:{
      url:req.url
    },
    template:`
    <div>Visited URL yes:{{url}}
    <button @click="alert('123')">click me!</button>
    </div>
    `
  })
  renderer.renderToString(apps,(err,html)=>{
    if(err) throw err
    res.send(html)
  })
})
app.listen(3000, ()=>{
  console.log('Please visit http://127.0.0.1:3000')
})

It is found that the button button is successfully displayed on the page, but unfortunately, the event is not successfully bound, and the click is invalid. In fact, except that the event is not bound, although the server has completed the rendering of vue, it has become a string when it is given to the client. We can't use a series of familiar features of vue applications, For example, data responsive update, what should we do? In order to solve the above problems, we need to introduce a new concept called isomorphism

6, Understanding isomorphism

A set of vue (react) code, which is executed once on the server and again on the client, is isomorphic

 const apps = new Vue({
    data:{
      url:req.url
    },
    template:`
    <div>Visited URL yes:{{url}}
    <button @click="alert('123')">click me!</button>
    </div>
    `
  })

The execution of the vue code shown above on the server side remains unchanged. As long as we re execute this code on the client side, we can have all the features of the original vue application. Indeed, but this process is too difficult. We just need to understand it now, The so-called isomorphism means that the same set of vue code is executed once on the server and again on the client

7, Nuxt JS framework usage

7.1 create project

nuxt.js is a server-side rendering framework that uses vue framework to develop applications, and provides out of the box functions https://www.nuxtjs.cn/

npm create nuxt-app <Project name>

Follow the prompts to select an item and complete the creation. Note that ssr should be selected in this step

7.2 start up project

npm run dev

7.3 viewing source code

Obviously, we see the actual rendering content on the web page, which is the rendering responsibility of the server

7.4 building home page

pages/index.vue

In nuxt In the project generated by JS, we still write single file components as before vue code, ElementUI components can also be used normally

<template>
  <div class="container">
    <Logo />
    <div class="articleList">
      <el-collapse>
        <el-collapse-item title="uniformity Consistency" name="1">
          <div>
            Be consistent with real life: be consistent with the process and logic of real life, and follow the language and concepts used by users;
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
export default {}
</script>

<style>
.container {
  padding: 0 200px;
}
.articleList {
  margin-top: 30px;
}
</style>

7.5 asynchronous acquisition

Introduction - Axios Module (nuxtjs.org)

1. asyncData method

The asyncData method is called before each loading of the component (limited to page components). It can be called before the server or route update. You can use the asyncData method to obtain data, nuxt JS will return the data returned by the data fusion component data method returned by asyncData to the current component

async asyncData({ $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
return { ip }
},
data(){
return {
name:'cp'
}
}
----After merging data data----
{
name:'cp',
ip
}
2. Get recommended music
<template>
  <div class="container">
   <ul class="images">
     <li v-for="item in ips" :key="item.id">
       {{item.name}}
       <img :src="item.picUrl" alt="">
     </li>
   </ul>
  </div>
</template>

<script>
export default {
  created () {
  },
  async asyncData ({ $axios }) {
    const ip = await $axios.$get('http://api.daqitc.net/personalized')
    console.log(ip.result)
    const ips = ip.result
    return { ips }
  }
}
</script>

<style>
.container {
  padding: 0 200px;
}
.articleList {
  margin-top: 30px;
}
.images li img{
  width: 200px;
}
</style>

3. Preview the effect and view the source code

source code

**Conclusion: * * we have completed using both vue development mode and server-side rendering mode, nice~

8, Summary

8.1 what do server-side rendering and client-side rendering refer to respectively? What are the characteristics?

SSR server renders web page content. The first screen generated by the server is short, which is conducive to seo. CSR client rendering vue and react frame rendering spa are both client rendering. The first screen rendering time is long, which is not conducive to seo

What is the essence of isomorphism?

A vue code is rendered once on the server side and then again on the client side. The server side rendering solves the problem of fast first screen display. The client side rendering needs to tie back the classic vue features such as event and response features. We can not only use the vue development mode, but also enjoy the advantages of the two rendering methods

8.3 Nuxt. How to implement asynchronous data acquisition (asyncData method) in JS?

asyncData function is a function built in the Nuxtjs framework. The execution result is fused with data and returned to the current group together
21737819506)]

**Conclusion: * * we have completed using both vue development mode and server-side rendering mode, nice~

8, Summary

8.1 what do server-side rendering and client-side rendering refer to respectively? What are the characteristics?

SSR server renders web page content. The first screen generated by the server is short, which is conducive to seo. CSR client rendering vue and react frame rendering spa are both client rendering. The first screen rendering time is long, which is not conducive to seo

8.2 what is the essence of isomorphism?

A vue code is rendered once on the server side and then again on the client side. The server side rendering solves the problem of fast first screen display. The client side rendering needs to tie back the classic vue features such as event and response features. We can not only use the vue development mode, but also enjoy the advantages of the two rendering methods

8.3 Nuxt. How to implement asynchronous data acquisition (asyncData method) in JS?

asyncData function is a function built in the Nuxtjs framework. The execution result is fused with data and returned to the current group together

Keywords: Javascript Vue

Added by Fireglo on Fri, 11 Feb 2022 04:14:23 +0200