Server side rendering (ssr)

1 Overview

1. What is SSR?

Vue.js is a framework for building client-side applications. By default, the Vue component's responsibility is to generate and manipulate the DOM in the browser. However, Vue also supports rendering components directly into HTML strings on the server side, returning them to the browser as a server-side response, and finally "hydrate" the static HTML on the browser side into an interactive client application.

A server-rendered Vue.js application can also be considered "isomorphic" or "universal" because most of the application's code runs on both the server and the client.

2. Why use SSR?

Compared with client-side single-page applications (SPA), the main advantages of SSR are:

Faster first-screen loading: This is especially important on slow internet connections or slow-running devices. Server-side rendered HTML doesn't have to wait for all JavaScript to be downloaded and executed before it's displayed, so your users will see the fully rendered page faster. In addition, the data retrieval process is completed on the server side on first access, which may have a faster database connection than retrieval from the client. This often results in higher core web metric scores and a better user experience, which can be critical for apps where first-screen load speed is directly related to conversion rates.

Unified mental model: You can develop the entire application using the same language and the same declarative, component-oriented mental model without having to switch back and forth between back-end templating systems and front-end frameworks.

Better SEO: Search engine crawlers can see the fully rendered page directly.

There are some trade-offs to consider when using SSR:

Development limitations. Browser-specific code can only be used in certain lifecycle hooks; some external libraries may require special handling to run in server-rendered applications.

More requirements related to build configuration and deployment. Server-side rendering applications require an environment that allows the Node.js server to run. Unlike completely static SPA, which can be deployed on any static file server.

Higher server load. Rendering a complete application in Node.js is more CPU intensive than just hosting static files, so if you anticipate high traffic, prepare for the corresponding server load and adopt a sensible caching strategy.

Before using SSR for your application, you should first ask yourself whether you really need it. This mainly depends on how important the first screen loading speed is to the application. For example, if you are developing an internal admin panel, the extra few hundred milliseconds during the initial load are not important to you, in which case there is not much need to use SSR. However, in scenarios where content display speed is extremely important, SSR can help you achieve the best initial loading performance possible.

2.SSR vs. SSG

Static-Site Generation (SSG), also known as pre-rendering, is another popular technique for building fast websites. If the data required to render a page server-side is the same for every user, then we can render it only once and do it ahead of time during the build process, rather than re-rendering the page every time a request comes in. The pre-rendered page is generated and hosted as a static HTML file by the server.

SSG retains the same performance as SSR applications: it brings excellent first-screen loading performance. At the same time, it is less expensive and easier to deploy than SSR applications because it outputs static HTML and resource files. The key word here is static: SSG can only be used for pages that consume static data, i.e. the data is known during build time and does not change across multiple deployments. Whenever the data changes, it needs to be redeployed.

If you're looking into SSR just to optimize the SEO of a few marketing pages (such as /, /about, /contact, etc.), then you probably want SSG instead of SSR. SSG is also great for building content-based websites, such as documentation sites or blogs. In fact, the website you are reading now was statically generated using VitePress, a static site generator powered by Vue.

3. Render an application

Let's take a look at the most basic practical example of Vue SSR.

Create a new folder, cd into
execute

npm init -y

Add "type": "module" to package.json to make Node.js run in ES modules mode.
Execute
npm install vue
Create an example.js file:

// 此文件运行在 Node.js 服务器上
import { createSSRApp } from 'vue'
// Vue 的服务端渲染 API 位于 `vue/server-renderer` 路径下
import { renderToString } from 'vue/server-renderer'

const app = createSSRApp({
  data: () => ({ count: 1 }),
  template: `<button @click="count++">{
   
   { count }}</button>`
})

renderToString(app).then((html) => {
  console.log(html)
})

Then run:
node example.js

It should print something like this to the command line:

<button>1</button>
renderToString() receives a Vue application instance as a parameter and returns a Promise. When the Promise resolves, the HTML rendered by the application is obtained. Of course, you can also use the Node.js Stream API or Web Streams API to perform streaming rendering.

We can then move the Vue SSR code into a server request handler function, which wraps the application's HTML fragments into complete page HTML. We will use express in the next few steps:

Execute npm install express
to create the following server.js file:
js

const express = require('express');
const { createSSRApp } = require('vue');
const { renderToString } = require('vue/server-renderer'); 

const server = express()

server.get('/', (req, res) => {
  const app = createSSRApp({
    data: () => ({ count: 1 }),
    template: `<button @click="count++">ssr测试按钮:{
   
   { count }}</button>`
  })

  renderToString(app).then((html) => {
    res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Vue SSR Example</title>
      </head>
      <body>
        <div id="app">${html}</div>
      </body>
    </html>
    `)
  })
})

server.listen(3000, () => {
  console.log('ready')
})

Finally, execute node server.js and access  http://localhost:3000. You should see the button on the page.

After running, it was found that the button button was successfully displayed on the page, but unfortunately, the event was not successfully bound and the click was invalid. In fact, in addition to the fact that the event was not bound, although the server side had completed the rendering of Vue, it had already been sent to the client. It has become a string. We cannot use a series of features of Vue applications that we are familiar with, such as responsive data update. So what should we do?

In order to solve the above problems, we need to introduce a new concept called isomorphism.

 

Guess you like

Origin blog.csdn.net/m0_67388537/article/details/131936303