Ionic、Angular、Cordova打包压缩Web项目 - 解决vendor.js过大问题

背景:项目采用 Ionic3 开发,打包成 Web 项目作为移动端、小程序访问,发现奇慢无比,可能需要 10s+ 才能打开网页,这个速度是不能忍的,分析了一下网络请求发现,时间主要耽误在 vendor.js 上,竟然有 4MB 多,所以必须要压缩了

一、问题分析

查看 Network 的加载时间,发现 vendor.js 就是罪魁祸首,竟然有 4.4 MB,加载了 16.05s,用户肯定以为网站崩溃了
Network加载分析
再看项目 build 完的代码结构,最大的确实就是 vendor.js 和 main.css 了
网站源码

二、查阅官网

官网Build 说明:https://ionicframework.com/docs/cli/commands/build

ionic build uses the Angular CLI. Use ng build --help to list all Angular CLI options for building your app. See the ng build docs for explanations. Options not listed below are considered advanced and can be passed to the ng CLI using the – separator after the Ionic CLI arguments. See the examples.

意思就是 Ionic 说:你直接看 Angular 官网吧,我们就是用的人家的 :
https://angular.io/cli/build

我们看到有下面这个参数

参数 说明
--prod=true|false When true, sets the build configuration to the production target. All builds make use of bundling and limited tree-shaking. A production build also runs limited dead code elimination.

加了 --prod参数后,angular-cli 会把用不到的包都删掉,其实就是 product 的缩写

三、实验验证

1. 命令行用法

ionic cordova build browser --prod

压缩后项目
vendor.js 大大减小到 500 多 K,整个 Web 项目也可以做到瞬间加载
压缩后项目

2. 访问测试

vendor.js 加载用了 2.56s,算是能接受的一个范围,整个网站在 3s 之内就会显示,不会一直白屏了,如果再结合 gzip 压缩一下内容,速度估计还有提升
在这里插入图片描述

四、其他优化

1. Nginx 开启 gzip 压缩

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;

2. Apache 开启 gzip 压缩

对图片等特殊文件不进行 gzip 压缩处理

复制代码
<IfModule mod_deflate.c>
# 告诉 apache 对传输到浏览器的内容进行压缩
SetOutputFilter DEFLATE
# 压缩等级 9
DeflateCompressionLevel 9
#设置不对后缀gif,jpg,jpeg,png的图片文件进行压缩
SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
</IfModule>

或者指定文件格式进行压缩:

<IfModule mod_deflate.c>
# 压缩等级 9
DeflateCompressionLevel 9
# 压缩类型 html、xml、php、css、js
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-javascript application/x-httpd-php
AddOutputFilter DEFLATE js css
</IfModule>

修改好后,保存 httpd.conf 文件,记得重启 apache,再刷新浏览器看请求,应该已经生效了!


参考链接

发布了87 篇原创文章 · 获赞 93 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/zhichaosong/article/details/90510657