经过 2 天的工作,我们成功地进行了缩小,并将多个 js 文件合并到一个文件中。
在我们的框架中,如果不存在,我们首先创建缩小文件。我们从 PHP/模板文件中加载相同的文件 <script src=''></script>
标签。
但是每次我们请求同一个 js 文件时,浏览器都会下载它(因为它显示 200 Ok 状态)但我们期望是 304(未修改),因为之前请求过该文件好吧。
我们可以做些什么来让浏览器缓存文件?
编辑 1:
<?php
$content = NULL;
$jsFiles = array(..);//all files
foreach($jsFiles as $file) {
$content .= file_get_contents($file);
}
$minifiedContents = jsMinify($content);
file_put_contents($MinifiedJsFilePath, $minifiedContents);//minified.js
?>
<html>
<head>
<title>Minification</title>
<script src="minified.js"></script>
</head>
</html>
最佳答案
您的服务器需要支持 If-Modified-Since
request header (和/或其他条件获取 header )。这些 header 由 Web 浏览器随每个 (conditional) get request 一起发送。 .
A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s)
本质上,您的服务器需要:
- 检查请求 header 中是否存在这些字段。
- 使用这些条件来确定是提供页面还是返回 HTTP 304 响应。
在 google 中搜索将为您提供大量 PHP 示例。 Like this one .
编辑:
将服务器逻辑与客户端逻辑和标记分开。
你可以这样做:
服务器:
创建一个 PHP 脚本(我们将其命名为 getjs.php
),它返回缩小后的 JS 内容,如果没有任何变化,则返回 304 响应:
<?php
if (/*Determine if need to return 304*/){
header('HTTP/1.0 304 Not Modified');
exit;
}
$content = NULL;
$jsFiles = array();//all files
foreach($jsFiles as $file) {
$content .= file_get_contents($file);
}
$minifiedContents = jsMinify($content);
header("content-type: application/javascript");
echo $minifiedContents;
?>
客户:
<script src="getjs.php"></script>
关于javascript - 通过在 php 中即时生成的浏览器缓存 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21331298/