使用PHP动态最小化Javascript


Minification of Javascript on the fly with PHP

我使用PHP动态删除HTML、CSS和javascript的额外空格和行:-在PHP文件的开头,我使用ob_start();

在脚本的末尾:-

echo preg_replace(array('/'s{2,}/', '/['t'n]/'), ' ', ob_get_clean() );

但在这之后,我的javascript代码就不起作用了。我在javascript中正确地使用了分号和括号,所以我想知道这段代码出了什么问题!以下是我的一点javascript,如果我不使用该函数删除多余的行,它就会起作用:-

function delfile(fileid)
    {
      var div = "f_" + fileid;
      var location = "/delfile/" + fileid;
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange=function()  {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
                    {
                        var patt = /Deleted/;
                        var text = xmlhttp.responseText;
                        if(patt.test(text))
                        {
                            var elem = document.getElementById(div);
                            elem.parentNode.removeChild(elem);
                        }
                    else    
                        {
                            alert('Some error deleting that');
                        }
                }
                            }
      xmlhttp.open("POST", location, true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.send("");
  }

在动态缩小所有代码后,此代码不起作用!它给出以下错误:Uncaught ReferenceError: show is not defined files:1onclick files:1

最小输出:<script>function delfile(fileid) { var div = "f_" + fileid; var location = "/delfile/" + fileid; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var patt = /Deleted/; var text = xmlhttp.responseText; if(patt.test(text)) { var elem = document.getElementById(div); elem.parentNode.removeChild(elem); } else { alert('Some error deleting that'); } } } xmlhttp.open("POST", location, true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(""); }</script>

我想xmlhttp.onreadystatechange=function() {附近有问题。

xmlhttp.onreadystatechange后面缺少一个分号,所以它看起来应该像这个

xmlhttp.onreadystatechange=function()  { ... };

尽管我认为最好的建议是不要使用这种缩小,因为你有意外错误的风险(比如你问的那个)。此外,我不确定你安全的几个字节是否值得这么麻烦。

如果你真的有充分的理由缩小你的js/html,那么我会找一些可靠的软件/库来做这件事。