首页 > 解决方案 > 如何缓存javascript文件

问题描述

在此处输入图像描述我有一个大约 9 到 8 年前使用“ pug ”技术构建的大型 Web 应用程序,近年来页面已添加到创新框架 (vue.js) 中现在在旧页面 (pug) 和一个 vue 页面,Webpack(版本 3.12)加载了一个 build.js 文件(3.8MB!),该文件位于 index.html 中,平均需要 9 秒的时间来加载,并且显着干扰了用户体验。

有什么办法可以将 build.js 保存在缓存中吗?或者,我很想知道是否有人有其他可以增强用户体验的想法

该网站的网络服务器是 Nginx

编辑:这是我的 nginx 文件(相关部分)

server {
    listen      80;
    server_name xxx.com;
    return 301 https://xxx$request_uri;
}

server {
    listen       443 ssl;
    server_name xxx.com;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 1000;
      location ~ ^/dist/(?:ico|css|js|gif|jpe?g|png)$ {
        expires 30d;
    }
    location ~ ^/public/(\d+)/(.+)$ {
         try_files /lbo_builds/build_$1/public/$1/$2 =404;
    }

    location ~ ^/export/data/(.+)$ {
        gzip_static always;
        add_header Content-Encoding gzip;
        add_header Content-disposition attachment;
        try_files /lbo_exported_files/$1.gz =404;
    }

    location /customer_upload_document_proxy {
        proxy_set_header Cookie JSESSIONID=$cookie_jba_session;
        proxy_pass xxx;
    }

    location / {
        expires off;
        add_header Cache-Control "max-age=0, no-store, no-cache, must-revalidate";

        proxy_set_header X-Forwarded-For $remote_addr;

        proxy_pass http://$backend_upstream$request_uri;
    }
}

标签: javascriptvue.jsnginxwebpackpug

解决方案


  1. 将单个大块拆分build.js为小块,以利用浏览器的并行下载。
  2. 使用 nginx 配置 gzip 压缩和缓存控制
server {
    listen      80;
    server_name xxx.com;
    return 301 https://xxx$request_uri;
}

server {
    listen       443 ssl;
    server_name xxx.com;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 1000;

    location ~ ^/public/(\d+)/(.+)$ {
         try_files /lbo_builds/build_$1/public/$1/$2 =404;
    }

    location ~ ^/export/data/(.+)$ {
        gzip_static always;
        add_header Content-Encoding gzip;
        add_header Content-disposition attachment;
        try_files /lbo_exported_files/$1.gz =404;
    }

    location /customer_upload_document_proxy {
        proxy_set_header Cookie JSESSIONID=$cookie_jba_session;
        proxy_pass xxx;
    }

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
        expires 30d;
        
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://$backend_upstream$request_uri;
    }

    location / {
        expires off;
        add_header Cache-Control "max-age=0, no-store, no-cache, must-revalidate";

        proxy_set_header X-Forwarded-For $remote_addr;

        proxy_pass http://$backend_upstream$request_uri;
    }


}

推荐阅读