配置PHP.ini
更改配置項(xiàng)(必須)auto_prepend_file = "C:\xampp\htdocs\auto_prepend_file.php"
更改配置項(xiàng)(可選)allow_url_include = On
auto_prepend_file.php文件內(nèi)容
<?php
/**
* 引入static文件
* @param {array|string} 相對(duì)路徑
* @param {string} 當(dāng)前執(zhí)行腳本所在的路徑__FILE__
*
*/
function import_static($files, $path=NULL){
// 更改當(dāng)前腳本的執(zhí)行路徑
$old_dir = getcwd();
$tmp_dir = (isset($path)) ? dirname($path): dirname(__FILE__);
chdir($tmp_dir);
// 整理包含文件
if (!is_array($files)) {
$tmp = array();
$tmp[] = $files;
$files = $tmp;
}
// 發(fā)送頭信息
if (isset($files[0])) {
if (stripos($files[0], '.js') !== false) {
$header_str = 'Content-Type: text/javascript';
} elseif (stripos($files[0], '.css') !== false) {
$header_str = 'Content-Type: text/css';
}
if (!ob_get_contents()) {
header($header_str);
}
}
// 引入包含文件
foreach($files as $key=>$value) {
require_once($value);
}
// 改回當(dāng)前腳本的執(zhí)行路徑
chdir($old_dir);
}
?>
使用方法
"a.js"、"b.js"和"../c.js"是待合并的JS文件,將其合并為base.js.php,則base.js.php中的代碼如下:
<?php
import_static(array(
'a.js',
'b.js',
'../c.js',
'../moduleB/all.js.php' // 也可引用.php文件
), __FILE__);
?>
在HTML頁(yè)面中使用<script type="text/javascript" src="base.js.php"></script>即可引入。
產(chǎn)品上線前,使用批處理文件進(jìn)行處理,主要做兩方面的工作
1.將"*.js.php"輸出到"*.js"文件,并刪除"*.js.php"。命令行:php *.js.php > *.js
2.將HTML頁(yè)面中對(duì)"*.js.php"的引用替換為"*.js"。preg_replace()
PS:import_static函數(shù)解決了PHP中include()處理相對(duì)路徑的問(wèn)題。
以上就是本文的全部?jī)?nèi)容了,更詳細(xì)的信息請(qǐng)期待后續(xù)文章