当我压缩脚本时 JavaScript 停止工作
我想压缩 2000 多行 javascript,并且我已经测试了 http://dean.edwards.name/ packer/ 和 http://closure-compiler.appspot.com/home 。
但在这两种情况下,压缩脚本都会给我带来错误。 错误的一个示例是 jQuery(document).Da 不是函数
。
为什么我的脚本优化后不起作用? 我可以做什么来优化/压缩我的脚本?
I want to compress my 2000+ lines of javascript and I have tested both http://dean.edwards.name/packer/ and http://closure-compiler.appspot.com/home.
But in both cases, the compressed script gives me errors.
An example of an error is jQuery(document).Da is not a function
.
Why isn't my script working after optimization?
And what can I do to optimize / compress my script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保每个 JavaScript 文件的开头都有分号。我知道这很奇怪,但原因如下:
您可能在一个文件中包含类似的内容:
在下一个文件中紧接着类似的内容(这是许多 jQuery 插件的外观):
它被压缩为:
这实际上调用了
someFunc
以function($){...}
作为参数。然后,它将接受返回的任何内容,并假设它是一个函数并使用jQuery
作为参数来调用它。这就是为什么大多数 jQuery 插件都以
;(function($){
开头。在每个文件的开头(或末尾,但要保持一致)放置分号将使您的脚本看起来像
:这样,您的脚本将按预期进行解释。
Make sure you have a semicolon at the beginning of every JavaScript file. Bizarre, I know, but here's why:
You might have something like this in one file:
followed by something like this in the next file (this is how many jQuery plugins look):
That gets compressed into this:
Which essentially calls
someFunc
withfunction($){...}
as it's argument. Then, it will take whatever is returned, and assume it is a function and call it withjQuery
as the argument.This is why most jQuery plugins start with
;(function($){
.Putting a semicolon at the beginning of every file (or the end, but make it consistent) will make your scripts look like:
That way, your scripts will be interpreted as intended.
您可以尝试在线 YUI 压缩机。这是谷歌上的第一个结果: http://www.refresh-sf.com/yui/< /a>
You could try an online YUI Compressor. This is the first result on google: http://www.refresh-sf.com/yui/
我也有同样的问题。每次我想缩小我的 javascript 文件(包括一些 jquery 插件)时,我都会收到错误。
首先,我尝试使用附加分号来解决问题,正如尼古拉德斯在他的上一篇文章中所解释的那样。即使有了他的建议,我也无法在没有错误的情况下缩小我的 js 文件。
之后我在每个 jquery-plugin 中更改了以下行并为我工作;
例如:
我已经简化为
i had the same problems. everytime i wanted to minify my javascript-files inclusive a few jquery-plugins i got an error.
first i tried to solve the problems with the addional semicolons as nicholaides explained in his last post. even with his advice i couldn't manage to minify my js-file without errors.
after that i changed the following line in every jquery-plugin and in worked for me;
for instance:
i have simplified to