

加载HTML
加载javascript(bundle.js)
执行javascript,开始请求接口
先建立和接口的HTTP/HTTPS连接(dns查询/tcp握手/TLS链接)
发送请求header,获取响应数据 ...
渲染数据,呈现给用户
我们用Vue/React + Webpack打包的js动辄300KB以上,步骤2会消耗一点时间。如果在 步骤2 进行中时,同步执行 步骤4 建立连接,就能节约一点点时间。
尤其在移动端,建立连接的时间占了大头,能省是省。
<link rel="preconnect"> 让浏览器预先建立连接。主流浏览器大多已支持:https://caniuse.com/#feat=link-rel-preconnect
做了一个简单的webpack插件: https://github.com/joaner/html-webpack-preconnect-plugin
// $ npm install html-webpack-preconnect-plugin --save-dev
var HtmlWebpackPreconnectPlugin = require('html-webpack-preconnect-plugin');
// webpack config
{
...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
// set the preconnect origins
preconnect: [
'http://api1.example.com',
'http://api2.example.com',
]
}),
// enabled preconnect plugin
new HtmlWebpackPreconnectPlugin(),
]
}这个插件做的事非常简单,就是插入到<head>里:
<!-- dist/index.html --> <head> ... <link rel="preconnect" href="http://api1.example.com"> <link rel="preconnect" href="http://api2.example.com"> </head>
我之前用HtmlWebpackPlugin的模板实现,但是略微有点繁琐,所以提取成了插件。
<!-- template.html --> <link rel="preconnect" href=<%= htmlWebpackPlugin.options.api1_origin %>>
