【发布时间】:2018-03-18 19:54:37
【问题描述】:
我有以下 JS(不是 jQuery),我想对其进行压缩(使用 header('Content-type: text/javascript') 保存在 PHP 文件中):
var $url = window.location.href;
$url = $url.toLowerCase().replace(/^(http(s)?\:\/\/)/g, ''),
$url = $url.split('/');
var $current_page = $url[$url.length - 1].replace(/(\?.*)?(\#.*)?/g, ''); // Current Page
document.addEventListener('DOMContentLoaded', function() {
if ($current_page === 'index.html') {
if (window.location.hash) {
var $current_hash = window.location.hash.substring(1);
} else {
window.location.hash = '';
}
// Ignore the code above, the important part is right below:
var $fp_imgs = document.querySelectorAll('img.-homepage-poster');
$fp_imgs.forEach(function($fp_img) {
var $imgs = [518966, 518967, 518968, 518969],
$rand = Math.floor($imgs.length * Math.random()),
$xmhr = new XMLHttpRequest();
var response = function($e) {
var $this = this,
$url_creator = window.URL || window.webkitURL,
$image_url = $url_creator.createObjectURL($this.response);
$fp_img.src = $image_url;
}
$xmhr.open('get', '../imgs/' + $imgs[$rand] + '.jpg', true);
$xmhr.responseType = 'blob';
$xmhr.onload = response;
$xmhr.send();
});
}
});
我使用ob_start 和以下正则表达式模式来压缩文件开头的代码:
ob_start(function($code) {
// return $code; # If the compression causing errors, do not compress
return preg_replace('(\s{2,})', ' ', preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\')\/\/.*))/', '', $code));
});
当它没有被压缩时,一切都很好。但是当我使用该模式时,我在控制台中收到以下错误:
语法错误:意外标记:标识符
“缩小”输出:
var $url = window.location.href; $url = $url.toLowerCase().replace(/^(http(s)?\:\/\/)/g, ''), $url = $url.split('/'); var $current_page = $url[$url.length - 1].replace(/(\?.*)?(\#.*)?/g, ''); document.addEventListener('DOMContentLoaded', function() { if ($current_page === 'index.html') { if (window.location.hash) { var $current_hash = window.location.hash.substring(1); } else { window.location.hash = ''; } var $fp_imgs = document.querySelectorAll('img.-homepage-poster'); $fp_imgs.forEach(function($fp_img) { var $imgs = [518966, 518967, 518968, 518969], $rand = Math.floor($imgs.length * Math.random()), $xmhr = new XMLHttpRequest(); var response = function($e) { var $this = this, $url_creator = window.URL || window.webkitURL, $image_url = $url_creator.createObjectURL($this.response); $fp_img.src = $image_url; } $xmhr.open('get', '../imgs/' + $imgs[$rand] + '.jpg', true); $xmhr.responseType = 'blob'; $xmhr.onload = response; $xmhr.send(); }); } });
我该如何解决这个问题?
非常感谢
【问题讨论】:
-
你从哪里得到这个压缩代码?
-
@MehdiBounya 移除 js cmets 我用了this answer,剩下的我写了
-
也许你没有正确缩小 js 代码,你要找的词是 Minify,有一些库可以为你做到这一点
-
@MehdiBounya 可能,但我不是在寻找繁重或复杂的东西,我需要一些简单的正则表达式解决方案。这可能吗?
-
当您在未压缩代码和压缩代码之间进行比较时,除了删除的 cmets,还有什么变化?你的线索就在那个比较中。
标签: javascript php compression