利用浏览器缓存 | 修改.htaccess 文件| - 不适用于 javascript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10511035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:38:22  来源:igfitidea点击:

Leverage browser caching | modifying .htaccess file | - not working for javascript files

javascript.htaccesscachingoptimizationbrowser-cache

提问by kad

I am trying to modify my .htaccess file by specifying an expiration for resources. It has worked for images but not for javascript files. When running GTMetrix it still recommends that the javascript files need expiration. I have tried "application/javascript" and "application/x-javascript" but to no avail.

我试图通过指定资源的到期时间来修改我的 .htaccess 文件。它适用于图像,但不适用于 javascript 文件。运行 GTMetrix 时,它仍然建议 javascript 文件需要过期。我试过“application/javascript”和“application/x-javascript”但无济于事。

Not sure what I am doing wrong.

不知道我做错了什么。

Here is my code:

这是我的代码:

     ## EXPIRES CACHING ##
    <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access 1 year"
    ExpiresByType image/jpeg "access 1 year"
    ExpiresByType image/gif "access 1 year"
    ExpiresByType image/png "access 1 year"
    ExpiresByType text/css "access 1 month"
    ExpiresByType application/pdf "access 1 month"
    ExpiresByType application/javascript "access 1 week"
    ExpiresByType application/x-shockwave-flash "access 1 month"
    ExpiresByType image/x-icon "access 1 year"
    ExpiresDefault "access 2 days"

    </IfModule>
    ## EXPIRES CACHING ##

回答by Amjad

Adding this will make it work.

添加这将使其工作。

ExpiresByType text/x-javascript "access plus 1 month"  
ExpiresByType application/javascript "access plus 1 month"  
ExpiresByType application/x-javascript "access plus 1 month"

回答by Craig London

Using the Network tab in the browsers inspector Chrome/FireFox/Opera, you can check the asset and see what kind of "Content Type" is being served.

使用浏览器检查器 Chrome/FireFox/Opera 中的网络选项卡,您可以检查资产并查看正在提供的“内容类型”类型。

In my case it was Content-Type:"text/javascript"

就我而言,它是 Content-Type:"text/javascript"

So I added 4 permutations of ExpiresByType to my .htaccess file

所以我在我的 .htaccess 文件中添加了 4 个 ExpiresByType 排列

ExpiresByType text/javascript "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"  
ExpiresByType application/x-javascript "access plus 1 month"

This solved my problem and I hope it will help others.

这解决了我的问题,我希望它会帮助其他人。