Prerender SPA Plugin
prerender-spa-plugin 是一个 webpack 插件用于在单页应用中预渲染静态 html 内容。因此,该插件限定了你的单页应用必须使用 webpack 构建,且它是框架无关的,无论你是使用 React 或 Vue 甚至不使用框架,都能用来进行预渲染。本文示例基于 Vue.js 2.0 + vue-router。
下文会从生成项目讲起,然后看下没有配置预渲染前的样子,再配置预渲染进行构建,对比前后的差别。
生成项目
首先生成一个项目并安装依赖。
vue init webpack vue-prerender-demo
cd vue-prerender-demo && npm install
组件开发过程我们不关注,具体可以查看示例源代码。开发完成视图如下。
路由配置
这是一个新闻应用的页面,包括了最新、最热两个列表页和一个文章页。路由配置如下。
new Router({
mode: 'history',
routes: [
{
path: '/',
component: Home,
children: [
{
path: 'new',
alias: '/',
component: () => import('@/components/New')
},
{
path: 'hot',
component: () => import('@/components/Hot')
}
]
},
{
path: '/article/:id',
component: Article
}
]
})
预渲染的单页应用路由需要使用 History 模式而不是 Hash 模式。原因很简单,Hash 不会带到服务器,路由信息会丢失。vue-router 启用 History 模式参考这里。
History 模式需要后台配置支持,最简单的是通过 nginx 配置 try_files 指令。
location / {
try_files $uri $uri/ /index.html;
}
没有配置预渲染前
配置完成后执行构建 npm run build,根据 nginx 配置,现在无论访问哪个路由都会返回 dist/index.html。
访问 / 路由。
可以看到,在 Fast 3G 网络下,首屏可见时间是 4.34s,页面至少在加载下面文件后才能被看到。
html
app.css - 样式
manifest.js - webpack manifest
vendor.js - 第三方库
app.js - 业务逻辑
0.js - 路由分包文件
其中 vendor 文件包含了引用的第三方库,文件规模较大。加载文件多,增加了白屏时间。所以,最有效的优化方案是减少首屏依赖文件。这里开始配置预渲染。
预渲染配置
安装 prerender-spa-plugin,安装时件略长,因为其依赖了 phantomjs,请耐心等待。
npm install prerender-spa-plugin --save-dev
我们只在生产环境中进行预渲染,修改 build/webpack.prod.conf.js,在配置插件的地方加入如下代码。
var path = require('path')
var PrerenderSpaPlugin = require('prerender-spa-plugin')
{
// ...
plugins: [
// ...
new PrerenderSpaPlugin(
// 输出目录的绝对路径--第一个参数
path.join(__dirname, '../dist'),
// 预渲染的路由--第二个参数
[ '/new', '/hot' ]
)
]
}
实例化 PrerenderSpaPlugin 需要至少两个参数,** 第一个参数是单页应用的输出目录,第二个参数指定预渲染的路由,这里执行了两个路由 /new 和 /hot 。**执行构建 npm run build。
预渲染效果
访问 /new 路由。
同样在 Fast 3G 网络下,首屏可见时间缩短至 2.30s。事实上,只要加载 html 和 app.css 文件,页面内容就能看到了。
dist
│ index.html
│
├─hot
│ index.html
│
├─new
│ index.html
│
└─static
对比构建完成目录,可以发现预渲染的目录多了两个文件 new/index.html, hot/index.html。
查看 new/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>vue-prerender-demo</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link href="/static/css/app.23611ac69a9fa48640e3bad8ceeab7bf.css" rel="stylesheet">
<script type="text/javascript" charset="utf-8" async="" src="/static/js/0.41194d76e86bbf547b16.js"></script>
</head>
<body>
<div id="app">
<div>
<div class="mu-appbar mu-paper-1">
<div class="left">
<i class="mu-icon material-icons">home</i>
</div>
<div class="mu-appbar-title">
<span>新闻</span>
</div>
<div class="right"></div>
</div>
...
</div>
</div>
<script type="text/javascript" src="/static/js/manifest.4410c20c250c68dac5bc.js"></script>
<script type="text/javascript" src="/static/js/vendor.d55f477df6e96ccceb5c.js"></script>
<script type="text/javascript" src="/static/js/app.f199467bd568ee8a197a.js"></script>
</body>
</html>
相比 index.html, new/index.html 中的
是有内容的,且 中多了当前路由分包的 js 文件。其余部分跟 index.html 一样。虽然有多个 html,但从 /new 跳转到其他路由时,还是单页内跳转的,不会有新的 html 请求。根据上面配置的 nginx 规则,路由对应的返回文件分别是:
/ -> index.html
/new -> new/index.html
/hot -> hot/index.html
/article/:id -> index.htm
其中,/new 和 /hot 路由返回的 html 包含了对应路由的内容,从而实现预渲染。没有配置预渲染的路由跟原来一样,还是访问 /index.html,请求脚本,动态渲染。
预渲染达到了类似服务端渲染的效果。区别在于预渲染发生在构建时,服务端渲染发生在服务器处理请求时。
prerender-spa-plugin 原理
那么 prerender-spa-plugin 是如何做到将运行时的 html 打包到文件中的呢?原理很简单,就是在 webpack 构建阶段的最后,在本地启动一个 phantomjs,访问配置了预渲染的路由,再将 phantomjs 中渲染的页面输出到 html 文件中,并建立路由对应的目录。
查看 prerender-spa-plugin源码
// 打开页面
page.open(url, function (status) {
...
// 没有设置捕获钩子时,在脚本执行完捕获
if (
!options.captureAfterDocumentEvent &&
!options.captureAfterElementExists &&
!options.captureAfterTime
) {
// 拼接 html
var html = page.evaluate(function () {
var doctype = new window.XMLSerializer().serializeToString(document.doctype)
var outerHTML = document.documentElement.outerHTML
return doctype + outerHTML
})
returnResult(html) // 捕获输出
}
...
})
预渲染骨架屏
本文实例中更多是变化的数据,时效性要求比较高,不太适合预渲染的场景。如果想用预渲染来减少白屏时间,让页面反馈更及时的话,可以预渲染骨架屏。
<template>
<div>
<new-list v-if="news.length > 0"></new-list>
<new-list-skeleton></new-list-skeleton>
</div>
</template>
请求 news 数据需要一定时间,所以插件在脚本执行完捕获的一般就是骨架屏。如果你想更灵活地指定捕获时机,可以使用自定义事件钩子,在组件挂载且请求数据前捕获。
{
mounted () {
document.dispatchEvent(new Event('sketelon-render-event'))
fetchNews()
}
}
访问页面时,用户首先看到预渲染的骨架屏(左图),等待 js 加载完成后,再拉取数据渲染出正确的内容。