时下很多网站大量的Javascript文件在用户访问的时候一股脑儿都塞给用户,导致用户访问网站的时候需要下载的js脚本很大很多,严重影响用户感受,所以我们需要压缩js文件。
有很多种压缩方法,其中我认为最简单的是网站http://javascriptcompressor.com/提供的在线压缩工具,可以尽量给你的js文件减肥:
1.第一个框是你的js代码输入框
2.有两个参数可选Base62转码,以及Shrink variables缩短你的变量名称
3.第二个TextArea框压缩之后的输出。
需要注意的是,你的javascript code必须正规合法,合法的源码如下:
注意每一句后面的分号,以及方法体后面的分号都必须有!
// sample code var $input, $output; // notice the semi-colon at the END of function declarations onload = function() { $input = document.getElementById("input"); $output = document.getElementById("output"); _clearAll(true); }; function _packScript() { $output.value = pack($input.value); }; function _clearAll($focus) { $output.value = $input.value = ""; // the "if" statement is NOT terminated with a semi-colon if ($focus) { $input.focus(); } };
将压缩之后的输出保存成js文件即可。你会发现你的文件瘦了很多!