官术网_书友最值得收藏!

Server-Side Rendering (SSR)

Server-Side Rendering allows us to take our frontend JavaScript application and render it to static HTML on the server. This is important as it allows us to significantly speed up our application as the browser only has to parse the critical HTML/CSS. Maximizing performance is a key component of modern day web applications and the expectation continues to grow with progressive web applications and projects such as AMP. Both React, Angular and Vue are capable of SSR using a variety of different patterns.

Let's take a look at how we can achieve a simple Server-Side rendered Vue application:

# Create a new folder named vue-ssr:
$ mkdir vue-ssr
$ cd vue-ssr

# Create a new file named server.js
$ touch server.js

# Install dependencies
$ npm install vue vue-server-renderer express

Inside server.js, we can create a new Vue instance and use the Vue renderer to output the content of our instance as an HTML:

const Vue = require("vue");
const server = require("express")();
const renderer = require("vue-server-renderer").createRenderer();

server.get("*", (req, res) => {
const app = new Vue({
data: {
date: new Date()
},
template: `
<div>
The visited time: {{ date }}
</div>`
});

renderer.renderToString(app, (err, html) => {
if (err) {
res.status(500).end("Internal Server Error");
return;
}
res.end(`
<!DOCTYPE html>
<html lang="en">
<head><title>Hello</title></head>
<body>${html}</body>
</html>
`);
});
});

server.listen(8080);

To run the application, type the following in the Terminal:

$ node server.js

We can then open this in our browser at http://localhost: 8080 and we'd see the current date and time on screen. This is a simple example but we were able to see our application rendered using the vue-server-renderer. Notice how we're not defining a target element to render content within our Vue instance; this is handled by the renderer.renderToString function.

You'll also notice that we have the data-server-rendered="true" attribute on our DOM node, which isn't present on a client-side rendered Vue application. This allows us to hydrate our client-side instance with our server-side instance, something we'll be looking at more detail in the later chapter(s) on Nuxt (https://nuxtjs.org/).

主站蜘蛛池模板: 陕西省| 泸定县| 循化| 华阴市| 花垣县| 洱源县| 白山市| 南阳市| 滕州市| 丹阳市| 横山县| 宾阳县| 罗源县| 太原市| 故城县| 宁阳县| 改则县| 安吉县| 大洼县| 雅江县| 常宁市| 罗源县| 安乡县| 教育| 廉江市| 南城县| 柳州市| 海丰县| 东阿县| 广宁县| 库伦旗| 乌拉特中旗| 怀远县| 云阳县| 景德镇市| 凌源市| 廉江市| 东源县| 黄梅县| 古交市| 灵寿县|