借助Code Splitting 提升单页面应用性能
近日的工作集中于一个单页面应用(Single-page application),在项目中尝试了闻名已久的Code splitting,收获极大,特此分享。
Why we need code splitting
SPA的客户端路由极大的减少了Server 与 Client端之间的Round trip,在此基础上,我们还可以借助Server Side Rendering 砍掉客户端的初次页面渲染时间(这里是SSR实现的参考链接:React,Angular2).
仍然有一个问题普遍存在着:随着应用复杂度/规模的增加,应用初始所加载的文件大小也随之增加。我们可以通过将文件分割成按需加载的chunks来解决这一问题,对于初始页面,只请求他所用到的模块的相关文件,等我们进入新的路由,或者使用到一些复杂的功能模块时,才加载与之相关的chunk。
借助于webpack与react-router(目前我的应用是基于React开发的),我们可以快速实现这些按需加载的chunks。
webpack
Webpack是非常火的一个module bundler,这里是一个很好的入门参考链接。
我们可以借助代码中定义split point以创建按需加载的chunk。
使用require.ensure(dependencies, callback)可以加载 CommonJs modules, 使用require(dependencies, callback)加载 AMD modules。webpack会在build过程中检测到这些split points,创建chunks。
React router
React router 是一个基于React且非常流行的客户端路由库。
我们能以plain JavaScript object或者declaratively的形式定义客户端路由。
Plain JavaScript way:
let myRoute = {
path: `${some path}`,
childRoutes: [
RouteA,
RouteB,
RouteC,
]
}
declaratively way:
const routes = (
<Route component={Component}>
<Route path="pathA" component={ComponentA}/>
<Route path="pathB" component={ComponentB}/>
</Route>
)
React router 可以实现代码的lazy load, 而我们正好可以把split points 定义在这些lazy load code中(参考链接)。
Code Splitting implement
below is a demo of create two on demand loaded chunks, chunk A will load once when enter rootUrl/A, chunk B will load once when enter rootUrl/B.
接下来的代码就是创建按需加载的chunks的例子,chunk A 只有当进入rootUrl/A才会加载,chunk B 只有当进入rootUrl/B才会加载。
routes
/* --- RootRoute --- */
...
import RouteA from './RouteA'
import RouteB from './RouteB'
export default {
path: '/',
component: App,
childRoutes: [
RouteA,
RouteB,
],
indexRoute: {
component: Index
}
}
/* --- RouteA --- */
...
export default {
path: 'A',
getComponent(location, cb) {
require.ensure([], (require) => {
cb(null, require(`${PathOfRelatedComponent}`))
}, 'chunkA')
}
}
/* --- RouteB --- */
...
export default {
path: 'B',
getComponent(location, cb) {
require.ensure([], (require) => {
cb(null, require(`${PathOfRelatedComponent}`))
}, 'chunkB')
}
}
client side code for client side render
...
import { match, Router } from 'react-router'
const { pathname, search, hash } = window.location
const location = `${pathname}${search}${hash}`
//use match to trigger the split code to load before rendering.
match({ routes, location }, () => {
render(
<Router routes={routes} history={createHistory()} />,
document.getElementById('app')
)
})
server code for server side rendering
...
app.createServer((req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error)
writeError('ERROR!', res)
else if (redirectLocation)
redirect(redirectLocation, res)
else if (renderProps)
renderApp(renderProps, res)
else
writeNotFound(res)
}).listen(PORT)
function renderApp(props, res) {
const markup = renderToString(<RoutingContext {...props}/>)
const html = createPage(markup)
write(html, 'text/html', res)
}
export function createPage(html) {
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>My Universal App</title>
</head>
<body>
<div id="app">${html}</div>
<script src="/__build__/main.js"></script>
</body>
</html>
`
}
实现中可能会遇到的坑
取决于你是如何写自己的模块的,你可能会遇到这个错误:React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of RoutingContext.在require()之后加一个.default即可。
如果你收到了这样的错误提示:require.ensure is not function, 增加一个polyfill即可: if (typeof require.ensure !== 'function') require.ensure = (d, c) => c(require),在Server端使用require来代替require.ensure.
谢谢,希望能指正我的错误!
最后附一张目前项目的chunks图:

借助Code Splitting 提升单页面应用性能的更多相关文章
- 借助 Vue 来构建单页面应用
原文: https://github.com/MeCKodo/vue-tutorial 主题 Vue.js (1/2)Vue构建单页应用最佳实战 前言 我们将会选择使用一些vue周边的库 1.使用no ...
- webpack优化之code splitting
作为当前风头正盛的打包工具,webpack风靡前端界.确实作为引领了一个时代的打包工具,很多方面都带来了颠覆性的改进,让我们更加的感受到自动化的快感.不过最为大家诟病的一点就是用起来太难了. 要想愉快 ...
- webpack 和 code splitting
Code Splitting指的是代码分割,那么什么是代码分割,webpack和code splitting又有什么样的联系呢? 使用npm run dev:"webpack-dev-ser ...
- Ember.js实现单页面应用程序
1.1.1 摘要 单页应用程序 (SPA) 是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序. SPA使用AJAX和HTML5创建流畅且响应迅速的Web应用程序,不会经常 ...
- Cloud Test 单页面即时监测功能上线!
什么是即时监测? 即时监测,顾名思义是指输入 URL 后能够立即进行监测并展示结果,无需注册. 如下图,在输入框内输入需要监测的 URL,点击免费监测,即可展示网页监测结果: 图中我们可以看到页面各个 ...
- 由单页面web应用引发的企业应用问题
由于单页面web应用的流行,client与server端之间都对应的产生了一些微妙的变化,比方,client原来仅仅是用来展示页面和理清逻辑,而现在逐渐转变成了一个可以进入驱动状态的应用程序. 未来的 ...
- 详细解剖大型H5单页面应用的核心技术点
项目 Xut.js 阐述下开发中一个比较核心的优化技术点,这是一套平台代码,并非某一个插件功能或者框架可以直接拿来使用,核心代码大概是6万行左右(不包含任何插件) .这也并非一个开源项目,不能商业使用 ...
- webpack Code Splitting浅析
Code Splitting是webpack的一个重要特性,他允许你将代码打包生成多个bundle.对多页应用来说,它是必须的,因为必须要配置多个入口生成多个bundle:对于单页应用来说,如果只打包 ...
- [转] react-router4 + webpack Code Splitting
项目升级为react-router4后,就尝试着根据官方文档进行代码分割.https://reacttraining.com/react-router/web/guides/code-splittin ...
随机推荐
- JS倒计时,距离某一日期还有多少时间
JS计算从现在到某个时刻还有多少时间,显示当前日期时间距离x年x月x日还有x天x小时x分钟x秒,如果给定时间比当前时间更早,则显示为距离2012-9-30已过去1天22小时26分30秒的格式,如果给定 ...
- ubuntu下的google拼音输入法(终结版)
声明:此文章是从我的51cto博客上搬至于此. Ubuntu下SCIM应该是最好的中文输入法了,它与搜狗差不多,下面介绍它的安装方法: 1)终端输入: sudo apt-get remove scim ...
- BZOJ_2730_ [HNOI2012]矿场搭建_点双联通分量
BZOJ_2730_ [HNOI2012]矿场搭建_点双联通分量 Description 煤矿工地可以看成是由隧道连接挖煤点组成的无向图.为安全起见,希望在工地发生事故时所有挖煤点的工人都能有一条出路 ...
- [HAOI 2010] 计数
[题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=2425 [算法] 类似与数位动态规划的思想 , 用组合数学进行简单推导即可 时间复杂度 ...
- [ZJU 2112] Dynamic Rankings
[题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1901 [算法] 首先 , 考虑没有修改操作 不妨建立可持久化线段树 , 第i棵树维护 ...
- codevs 2102 石子归并2
传送门 2102 石子归并 2 时间限制: 10 s 空间限制: 256000 KB 题目等级 : 黄金 Gold 题目描述 Description 在一个园形操场的四周摆放N堆石子,现要将 ...
- C++之输入输出流和文件传输流
1.流的控制 iomanip 在使用格式化I/O时应包含此头文件. stdiostream 用于混合使用C和C + +的I/O机制时,例如想将C程序转变为C++程序 2.类 ...
- 条件变量pthread_cond_wait()和pthread_cond_signal()详解
条件变量 条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起:另一个线程使"条件成立" ...
- poj1236学校网络——连通块
题目:http://poj.org/problem?id=1236 通过传输文件的特点可以看出要先求强联通分量,缩点: 问题1:即缩点后入度为0的点,从它们开始传文件可以传给所有学校: 问题2:对于所 ...
- 2、webpack基础配置
我们需要安装webpack 还需要安装webpack cli 这两个都是我们的开发依赖 这里我们一般会加一个-D表示上线的时候不需要他们两个包 安装我们的webpack 先初始化一下,记住我们的安装依 ...