如何使用php指令碼給html中引用的js和css路徑打上版本號碼,jscss_PHP教程

來源:互聯網
上載者:User

如何使用php指令碼給html中引用的js和css路徑打上版本號碼,jscss


在搜尋引擎中搜尋索引鍵.htaccess 緩衝,你可以搜尋到很多關於設定網站檔案快取的教程,通過設定可以將css、js等不太經常更新的檔案快取在瀏覽器端,這樣訪客每次訪問你的網站的時候,瀏覽器就可以從瀏覽器的緩衝中擷取css、js等,而不必從你的伺服器讀取,這樣在一定程度上加快了網站的開啟速度,又可以節約一下你的伺服器流量。

具體文字說明不給大家多說了,下面通過代碼執行個體給大家講解。

比如


中的href和src加上版本


當然如果不是前後端 分離得乾乾淨淨的,就沒必要這麼額外的這樣自己在寫個指令碼去打版本。

打版本的好處:

解決外部參考檔案即時更新問題。比如

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){  //["", "../js/config.js", "?is=new"]  /*/<\/script>/*/  $str = $match[0];  $pattern = '/(<\/script>)/';  return $this->callbackMatch($str, $pattern); } /**  * 匹配到css節點  * @param array $match 匹配到的css  * @return string 處理好的css  */ protected function callbackCss($match){  // '';  $str = $match[0];  $pattern = '/()/';  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>/';*/  $temp = explode('.', $file) ;  if ( ! $this->isNeedReplacePostFix(array_pop( $temp )) ) {return;}  $content = null;  $content = file_get_contents($file);  $content = preg_replace_callback('/<\/script>/', array(&$this, 'callbackScript'), $content);  $content = preg_replace_callback('//', 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();}

http://www.bkjia.com/PHPjc/1073129.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1073129.htmlTechArticle如何使用php指令碼給html中引用的js和css路徑打上版本號碼,jscss 在搜尋引擎中搜尋索引鍵.htaccess 緩衝,你可以搜尋到很多關於設定網站檔案快取...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.