当前位置:   article > 正文

Ionic、Angular、Cordova打包压缩Web项目 - 解决vendor.js过大问题_angular 项目启动时vendor.js 文件特别大

angular 项目启动时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|falseWhen 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
  • 1

压缩后项目
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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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


参考链接

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/749054
推荐阅读
相关标签
  

闽ICP备14008679号