关于项目第一次访问加载速度慢的问题(angular)

655 阅读1分钟

项目打包后的文件,打包命令ng build --prod

image.png

打包之后main.xxx.js这个文件的大小高达5.52M。 测试首次访问就这个main文件加载速度在4s左右,网速快可能就2,3s,网速慢就很慢

解决方案,在不改webpack 配置的情况下,做这么几件事

  1. 确保所有的模块都是懒加载,页面从component改成module,然后懒加载

ad4c6b1da96833d38440cf0afa8e884.png

  1. 删掉没有用的依赖

59d85427d80b7102d9457b84e07dc6a.png

  1. nginx配置gzip

nginx配置文件

server {
    listen       443 ssl;
    server_name  asgardcq1.cn.hpicorp.net;
    ssl_certificate      /usr/local/httpsSSL/server.crt;
    ssl_certificate_key  /usr/local/httpsSSL/server.key;
    ssl_session_timeout  5m;
    ssl_session_cache    shared:SSL:1m;
    ssl_ciphers          ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:aNULL:!MD5:!ADH:!RC4;
    ssl_protocols        TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers  on;
 
    location / {

	gzip on;
	gzip_http_version 1.1;
	gzip_comp_level 3;	    
	gzip_vary on;
	gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png image/x-ms-bmp;
	
        root   /home/dist/IURS;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
}

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

 #   location / {
 #       root   /usr/share/nginx/html;
 #       index  index.html index.htm;
 #   }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
#    location = /50x.html {
#        root   /usr/share/nginx/html;
#    }

    location / {
        root   /home/dist/IURS;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html; 
    }
}

server {
    listen       8080;
    server_name  localhost;
    location / {
        root   /home/deploy/IURS;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }


    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}


只有5行内容,随便百度一下相关的gzip配置加上去就行。 jingyan.baidu.com/article/bea…

最后实测,首次加载速度缩小到几百毫秒,就很棒!

顺便一提,gzip_http_version 对应的http协议版本可以通过浏览器开发者工具network查看

image.png