javascript - 如何缓存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;
}
}
解决方案
- 将单个大块拆分
build.js
为小块,以利用浏览器的并行下载。 - 使用 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;
}
}
推荐阅读
- ios - 使用 CodeMagic 部署时如何增加 Flutter IOS 应用程序的内部版本号
- python - 网页上可以看到评论,但是 BeautifulSoup 返回的 html 对象不包含评论部分
- firebase - 如何在颤动中更改 StreamBuilder 中特定切换开关的状态
- google-sheets - 如何摆脱导入范围中的空单元格并按人排序?
- c++ - 使用带有自定义构造函数的 std::set 自定义比较器
- php - 如何在 PHP 中使用 ECDSA(NIST 曲线 P-256/SHA-256)签署 SAML 2.0 AuthnRequest
- vue.js - 是否有特定的方法我必须从 vue 组件调用 vuex 操作?
- regex - 检查您的 elemMatch 正则表达式条件是否有效
- python - 安装 DREAM 时出错
- python - 在while循环中定义变量