Table of Contents
如何使用php脚本给html中引用的js和css路径打上版本号,jscss
Home Backend Development PHP Tutorial How to use php script to add version numbers to js and css paths referenced in html, jscss_PHP tutorial

How to use php script to add version numbers to js and css paths referenced in html, jscss_PHP tutorial

Jul 12, 2016 am 09:04 AM
css html js js script php script Version path

如何使用php脚本给html中引用的js和css路径打上版本号,jscss

在搜索引擎中搜索关键字.htaccess 缓存,你可以搜索到很多关于设置网站文件缓存的教程,通过设置可以将css、js等不太经常更新的文件缓存在浏览器端,这样访客每次访问你的网站的时候,浏览器就可以从浏览器的缓存中获取css、js等,而不必从你的服务器读取,这样在一定程度上加快了网站的打开速度,又可以节约一下你的服务器流量。

具体文字说明不给大家多说了,下面通过代码实例给大家讲解。

比如

<link rel="stylesheet" type="text/css" href="./css/globel.css">
<script src="./js/config.js"></script>
Copy after login

中的href和src加上版本

<link rel="stylesheet" type="text/css" href="./css/globel.css&#63;eslc-app=3-0-2">
<script src="./js/config.js&#63;eslc-app=3-0-2"></script>
Copy after login

当然如果不是前后端 分离得干干净净的,就没必要这么额外的这样自己在写个脚本去打版本。

打版本的好处:

解决外部引用文件实时更新问题。比如

pc端上主要体现在 iframe中的外部引用文件不会实时更新。

wap端上部分app也是比如微信。 如果你的网页是嵌到自己的app,那也更不用说了。

用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&#63;is=new"></script>", "../js/config.js", "&#63;is=new"]
  /*/<script.*&#63;src=\"(.*&#63;)(\&#63;.*&#63;|\&#63;)&#63;\".*&#63;><\/script>/*/
  $str = $match[0];
  $pattern = '/(<script.*&#63;src=\")(.*)&#63;(\"><\/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.*&#63;href=\")(.*)&#63;(\".*&#63;>)/';
  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('&#63;', $third[2]);
  $len  = count($arr);
  $versionName = $this->versionName;
  $version = $this->version;
  if ($len === 1) {//没有问号
   $arr[0] .= '&#63;'. $versionName. '='. $version;
  }else{//有问号
   if (preg_match('/(^|\&)'. $versionName.'=(.*&#63;)($|\&)/', $arr[1])) {//存在
    $arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*&#63;)($|\&)/', '$1'. $versionName.'='. $version. '$3', $arr[1]);
    $arr[0] .= '&#63;'. $arr[1];
   }else{//不存在
    $arr[0] .= '&#63;'. $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('&#63;', $third[2]);
  $len  = count($arr);
  $versionName = $this->versionName;
  if ($len > 1 && strpos($arr[1], $versionName. '=') !== false) {
   $arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*&#63;)($|\&)/', '$1', $arr[1]);
   substr($arr[1], -1) === '&' && ($arr[1] = substr($arr[1], 0, -1));
   $arr[0] .= strlen($arr[1]) > 0 &#63; '&#63;'. $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.*&#63;src=\"(.*&#63;)(\&#63;.*&#63;|\&#63;)&#63;\".*&#63;><\/script>/';*/
  $temp = explode('.', $file) ;
  if ( ! $this->isNeedReplacePostFix(array_pop( $temp )) ) {return;}
  $content = null;
  $content = file_get_contents($file);
  $content = preg_replace_callback('/<script.*&#63;><\/script>/', array(&$this, 'callbackScript'), $content);
  $content = preg_replace_callback('/<link.*&#63;type="text\/css".*&#63;>/', 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;
  }
 }
}
Copy after login

使用:

$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();
}
Copy after login

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1073129.htmlTechArticle如何使用php脚本给html中引用的js和css路径打上版本号,jscss 在搜索引擎中搜索关键字.htaccess 缓存,你可以搜索到很多关于设置网站文件缓存...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles