我目前正在缩小 JS 文件以提高页面速度。除了两个之外,我已经能够找到适用于几乎所有 js 文件的最简单方法。问题出在我试图在我的网站上实现的 wmd 编辑器的 js 文件。 js 文件 wmd.js
和 showdown.js
没有被 scripts.php
中的函数压缩和缓存。我用 Firebug 工具检查,在 scripts.php
的响应 header 中,这两个文件都没有包含在最终压缩的 js 文件中。
我压缩这些 js 文件(wmd & showdown)并将其合并为一个的过程有什么问题? EXAMPLE SITE
js/scripts.php-负责js文件的压缩和缓存
<?php
error_reporting(E_ERROR);
// see http://web.archive.org/web/20071211140719/http://www.w3.org/2005/MWI/BPWG/techs/CachingWithPhp
// $lastModifiedDate must be a GMT Unix Timestamp
// You can use gmmktime(...) to get such a timestamp
// getlastmod() also provides this kind of timestamp for the last
// modification date of the PHP file itself
function cacheHeaders($lastModifiedDate) {
if ($lastModifiedDate) {
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModifiedDate) {
if (php_sapi_name()=='CGI') {
Header("Status: 304 Not Modified");
} else {
Header("HTTP/1.0 304 Not Modified");
}
exit;
} else {
$gmtDate = gmdate("D, d M Y H:i:s \G\M\T",$lastModifiedDate);
header('Last-Modified: '.$gmtDate);
}
}
}
// This function uses a static variable to track the most recent
// last modification time
function lastModificationTime($time=0) {
static $last_mod ;
if (!isset($last_mod) || $time > $last_mod) {
$last_mod = $time ;
}
return $last_mod ;
}
lastModificationTime(filemtime(__FILE__));
cacheHeaders(lastModificationTime());
header("Content-type: text/javascript; charset: UTF-8");
ob_start ("ob_gzhandler");
foreach (explode(",", $_GET['load']) as $value) {
if (is_file("$value.js")) {
$real_path = mb_strtolower(realpath("$value.js"));
if (strpos($real_path, mb_strtolower(dirname(__FILE__))) !== false || strpos($real_path, mb_strtolower(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR)) !== false) {
lastModificationTime(filemtime("$value.js"));
include("$value.js");echo "\n";
}
}
}
?>
我调用 compressed.js 的方式
<script type = "text/javascript" src = "js/scripts.php?build=12345&load=wmd,showdown"></script>
最佳答案
我想问题出在语句 include("$value.js");echo "\n";
这样,如果包含的 javascript 文件至少包含一个“”字符串,并且如果您在“php.ini”配置文件中启用了“short_open_tag”选项,则部分javascript 代码正在从 PHP 解释器中被解析,就好像它是 PHP 代码一样,可能会抛出语法错误并因此忽略后续的包含。
查看“prettify.js”源代码,我发现有效地存在“”第 471 行的字符串。
也许将行 include("$value.js");echo "\n";
更改为 readfile("$value.js");echo "\n";
应该可以解决问题。
关于php - 使用 PHP- 文本编辑器压缩和合并 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11836189/