使用PHP脚本为HTML引用的JS和CSS文件添加版本号
作者:窗边听雨时间:2026-10-30 03:05:09浏览:530
本文介绍如何利用PHP脚本自动为HTML中引用的CSS和JS文件添加版本号,以解决浏览器缓存导致的文件更新不及时问题。通过示例代码展示如何在前后端未完全分离的场景下,实现外部引用文件的实时更新,特别适用于PC端iframe及移动端App内嵌网页场景。
浏览器缓存与文件版本控制的必要性
通过搜索引擎查找.htaccess缓存相关教程,可配置网站文件缓存。将CSS、JS等低频更新文件缓存至浏览器端,访客访问时直接从本地缓存加载而非服务器读取,从而提升网站打开速度并节省服务器流量。
此处省略文字说明,直接通过代码实例进行讲解。
例如
<link rel="stylesheet" type="text/css" href="./css/globel.css">
<script src="./js/config.js"></script>
为href和src属性添加版本号
<link rel="stylesheet" type="text/css" href="./css/globel.css?eslc-app=3-0-2">
<script src="./js/config.js?eslc-app=3-0-2"></script>
PHP脚本实现资源版本号自动注入
若前后端未完全分离,则无需额外编写脚本来手动打版本号。
添加版本号的优势:
解决外部引用文件的实时更新问题。例如
在PC端,主要体现为iframe内的外部引用文件无法实时更新。
在WAP端,部分App如微信环境。若网页嵌入自有App,则更需处理此问题。
PHP类库实现与调用示例
使用PHP编写了一个类
//生成版本
//清除版本
class ReplaceVersion{
protected $filePostFixs = array();
protected $versionName = null;
protected $version = null;
protected $path = null;
/**
* @param mixed $configs
* @param [type] $profix [description]
* @param [type] $path [description]
*/
public function __construct($configs, $profix, $path){
if (!$this->isCanRun()) {
$this->error('必须在内网环境 10.10.0开头才可运行'); //exit;
}
$this->setVersion($configs);
$this->setFilePostFix($profix);
$this->path = $path;
}
protected function isCanRun(){
if (strpos($_SERVER['HTTP_HOST'], '10.10.0') !== false) {
return true;
}
return false;
}
/**
* 匹配到script节点
* @param array $match 匹配到的script
* @return string 处理好的script
*/
protected function callbackScript($match){
//["<script src="../js/config.js?is=new"></script>", "../js/config.js", "?is=new"]
/*/<script.*?src=\"(.*?)(\?.*?|\?)?\".*?><\/script>/*/
$str = $match[0];
$pattern = '/(<script.*?src=\")(.*)?(\"><\/script>)/';
return $this->callbackMatch($str, $pattern);
}
/**
* 匹配到css节点
* @param array $match 匹配到的css
* @return string 处理好的css
*/
protected function callbackCss($match){
// '<link rel="stylesheet" type="text/css" href="../css/globel.css">';
$str = $match[0];
$pattern = '/(<link.*?href=\")(.*)?(\".*?>)/';
return $this->callbackMatch($str, $pattern);
}
/**
* 回调模式匹配
* @param string $str
* @param string $pattern
* @return string
*/
protected function callbackMatch($str, $pattern){
switch ($this->dealFlag) {
case 'replace':
return $this->replaceCallbackMatch($str, $pattern);
case 'clean':
return $this->cleanCallbackMatch($str, $pattern);
default:
$this->error('非法模式');
}
}
/**
* 替换版本
* @param string $str 待处理的string
* @param string $pattern 正则
* @return string 处理后的string
*/
protected function replaceCallbackMatch($str, $pattern){
if (!preg_match($pattern, $str, $third)) {
return $str;
}
$arr = explode('?', $third[2]);
$len = count($arr);
$versionName = $this->versionName;
$version = $this->version;
if ($len === 1) {//没有问号
$arr[0] .= '?'. $versionName. '='. $version;
}else{//有问号
if (preg_match('/(^|\&)'. $versionName.'=(.*?)($|\&)/', $arr[1])) {//存在
$arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*?)($|\&)/', '$1'. $versionName.'='. $version. '$3', $arr[1]);
$arr[0] .= '?'. $arr[1];
}else{//不存在
$arr[0] .= '?'. $arr[1]. '&'. $versionName. '='. $version;
}
}
return $third[1]. $arr[0]. $third[3];
}
/**
* 清除版本
* @param string $str 待清除的版本
* @param string $pattern 正则
* @return string 清除后的string
*/
protected function cleanCallbackMatch($str, $pattern){
if (!preg_match($pattern, $str, $third)) {
return $str;
}
$arr = explode('?', $third[2]);
$len = count($arr);
$versionName = $this->versionName;
if ($len > 1 && strpos($arr[1], $versionName. '=') !== false) {
$arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*?)($|\&)/', '$1', $arr[1]);
substr($arr[1], -1) === '&' && ($arr[1] = substr($arr[1], 0, -1));
$arr[0] .= strlen($arr[1]) > 0 ? '?'. $arr[1] : '';
$str = $third[1]. $arr[0]. $third[3];
}
return $str;
}
/**
* 执行
*/
protected function run(){
if ($this->path == '') {
$this->error('empty path');
return ;
}
if (is_dir($this->path)) {
$this->setDirFilesVersion( $this->path );
}else if(is_file($this->path)){
$this->setFileVersion( $this->path );
}else{
$this->error('error path');
}
}
/**
* 添加版本
*/
public function replace(){
$this->dealFlag = 'replace';
$this->run();
echo 'replace success';
}
/**
* 清除版本
*/
public function clean(){
$this->dealFlag = 'clean';
$this->run();
echo 'clean success';
}
protected function success(){
}
protected function error($errorMsg){
echo $errorMsg;
exit();
}
protected function setDirFilesVersion($dir){
$handle = null;
$file = null;
if ( $handle = opendir($dir)) {
while ( false !== ($file = readdir($handle)) ) {
if ($file === '.' || $file === '..' || strpos($file, '.') === -1 ) {continue;}
$this->setFileVersion($file);
}
}
}
protected function setFileVersion($file){
$temp = null;
/*$pattern = '/<script.*?src=\"(.*?)(\?.*?|\?)?\".*?><\/script>/';*/
$temp = explode('.', $file) ;
if ( ! $this->isNeedReplacePostFix(array_pop( $temp )) ) {return;}
$content = null;
$content = file_get_contents($file);
$content = preg_replace_callback('/<script.*?><\/script>/', array(&$this, 'callbackScript'), $content);
$content = preg_replace_callback('/<link.*?type="text\/css".*?>/', array(&$this, 'callbackCss'), $content);
// highlight_string($content);
file_put_contents($file, $content);
}
/**
* 获得版本
* @param mixed $configs array( 'versionName' : 'version') || $versionName
*/
protected function setVersion($configs){
// last_wap_version = '3-0-0',
// wap_version = '3-0-1',
if (is_array($configs) && $configs > 0) {
foreach ($configs as $key => $value) {
$this->version = $value;
$this->versionName = $key;
}
}else if(is_string($configs) && $configs != ''){
$configs = explode(',', $configs);
$this->versionName = $configs[0];
count($configs) == 2 && ($this->version = $configs[1]);
}else{
$this->error('the version is empty');
}
}
/**
* 通过后缀判断该文件是否要添加或清除版本
* @param string $profix 后缀
* @return boolean true | false
*/
protected function isNeedReplacePostFix($profix){
if (in_array($profix, $this->filePostFixs)) {
return true;
}
return false;
}
/**
* 设置需要操作的后缀
*/
public function setFilePostFix($profix){
if (is_array($profix)) {
count($profix) > 0 && ( $this->filePostFixs = array_merge($this->filePostFixs, $profix) );
}else if(is_string($profix)){
$this->filePostFixs[] = $profix;
}
}
}
使用方法:
$dir = __DIR__;
$is_clean = false;
//$is_clean = true;
//第一个参就是版本信息, 第二个就是要匹配的文件后缀, 第三个是要匹配的目录或者文件
if ($is_clean) {//清除版本
$configs = 'eslc-wap';
$replaceObj = new ReplaceVersion($configs, array('html'), $dir);
$replaceObj->clean();
}else{//添加或替换版本
$configs = array('eslc-wap' => '1.0.1');//也可以写成 $configs = 'eslc-wap, 1.0.1';
$replaceObj = new ReplaceVersion($configs, array('html'), $dir);
$replaceObj->replace();
}
作者最新文章
anime.js 快速入门:怎么引入库并编写第一个 DOM 动画
2026-11-05 14:22:43
在线JS解密后变量名仍乱码?结合浏览器DevTools调试还原
2026-11-04 20:26:01
怎么在浏览器中运行JavaScript代码并查看输出结果
2026-11-04 09:07:33
JS 获取屏幕分辨率:window.screen.width 与 height 用法
2026-11-04 08:52:48
为什么推荐用DOMContentLoaded代替window.onload初始化JS
2026-11-04 08:42:33
