php - php 的 `filemtime` 对于浏览器缓存或缓存清除来说是个好主意吗?

标签 php caching browser-cache

我正在使用 php 的 filemtime 向文件添加版本,这是一个好主意吗?

<link rel="stylesheet" href="css/custom.css?v=<?=filemtime("./css/custom.css")?>"/>
<script src="js/custom.js?v=<?=filemtime("js/custom.js")?>"></script>

这显示在来源中,例如

<link rel="stylesheet" href="css/custom.css?v=1564681659"/>
<script src="js/custom.js?v=1564599819"></script>

放置 ?v?ver 是否相同?

P.S:我正在对 .js 和 css 文件、bootstrap、jquery 等执行相同的操作(尽管只是所有本地文件)。

最佳答案

来自HTML5 ★ Boilerplate Docs :

What is ?v=1" '?v=1' is the JavaScript/CSS Version Control with Cachebusting

Why do you need to cache JavaScript CSS? Web page designs are getting richer and richer, which means more scripts and stylesheets in the page. A first-time visitor to your page may have to make several HTTP requests, but by using the Expires header you make those components cacheable. This avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often used with images, but they should be used on all components including scripts, stylesheets etc.

How does HTML5 Boilerplate handle JavaScript CSS cache? HTML5 Boilerplate comes with server configuration files: .htacess, web.config and nginx.conf. These files tell the server to add JavaScript CSS cache control.

When do you need to use version control with cachebusting? Traditionally, if you use a far future Expires header you have to change the component's filename whenever the component changes.

How to use cachebusting? If you update your JavaScript or CSS, just update the "?v=1" to "?v=2", "?v=3" ... This will trick the browser think you are trying to load a new file, therefore, solve the cache problem.

话虽这么说,您可以使用各种东西来版本化文件。使用 filemtime 是一个很好的方法。我相信这是我见过人们使用的最主流的方式之一。您可以离开它,并且知道它始终会正常工作并且很快不会发生冲突。我不知道 ?v?ver 之间有什么区别,但 ?v 是 90% 的应用程序中使用的那个。我见过的案例,也许更多。希望这会有所帮助。

关于php - php 的 `filemtime` 对于浏览器缓存或缓存清除来说是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315721/

相关文章:

javascript - 更改第二个组合框的数据,更改第一个组合框的数据

java - 如何修改实体管理器的查询缓存?

javascript - Backbone.js 解析未修改的响应

javascript - 将图像保留在内存中是否可以防止该图像的缓存过期?

php - 上传图片然后使用 php 将位置保存在 MySQL 数据库中。

php - 使用php提取文件的元数据

php - 使用 FB Graph API 为特定页面创建 Facebook 事件

javascript - 将 "hand-made"响应放入缓存中

php - 有关如何更改静态 Assets 的文件名以防止浏览器缓存的 Assets 文件版本过时的想法

javascript - 通过在 php 中即时生成的浏览器缓存 JS 文件