【Angular】使Angular加载速度快一些

Posted by ARTROY on 2019-09-12

Angular 首屏加载速度过慢,发现开启服务或打包后文 main.js 等文件过大,需要压缩文件使 Angular 加载快一些,可以减少图片大小、外链图片、压缩代码等。

Angular版本:^6
Angular-cli版本:^8

一、执行AOT

执行以下代码,可以看到:

1
2
ng serve
ng build

压缩前

执行以下代码明显看到以下文件缩小了:

1
2
3
4
5
6
7
8
9
10
11
// 默认开启aot
ng serve --prod || ng serve --prod --aot
ng build --prod || ng build --prod --aot

// UglifyJs能够有效的移除那些未使用的代码
ng build --prod (--build-optimizer包含该命令)
// 修改url地址 index.html中修改基本标记(<base href="/">) 与 index中文件的加载路径
ng build --base-href /tracker/
// 修改打包输出地址
ng build -op dist/example
ng build --output-path=dist/example

压缩前

nginx优化

(1)在nginx加上以下代码实现缓存:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
location ~* \.(gif|jpe?g|png|ico|swf)$ {
# d - 天
# h - 小时
# m - 分钟
expires 168h;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

# 由于js和css文件需要改动,设置的时间为5分钟
location ~* \.(css|js)$ {
expires 5m;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

(2)添加gzip压缩参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
gzip  on;
gzip_static on;
gzip_comp_level 2;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

# Disable for IE < 6 because there are some known problems
gzip_disable "MSIE [1-6].(?!.*SV1)";

# Add a vary header for downstream proxies to avoid sending cached gzipped files to IE6
gzip_vary on;

nginx优化



支付宝打赏 微信打赏

欣赏此文,打赏一下



-->