Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript stops working when I compress my script

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?

like image 312
Steven Avatar asked Nov 17 '09 02:11

Steven


2 Answers

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:

function someFunc() {
   ...
}

followed by something like this in the next file (this is how many jQuery plugins look):

(function($) {
   ...
})(jQuery);

That gets compressed into this:

function someFunc(){ }( function($){...} )(jQuery);

Which essentially calls someFunc with function($){...} as it's argument. Then, it will take whatever is returned, and assume it is a function and call it with jQuery 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:

;function someFunc(){ }; (function($){...})(jQuery);

That way, your scripts will be interpreted as intended.

like image 123
nicholaides Avatar answered Oct 21 '22 09:10

nicholaides


You could try an online YUI Compressor. This is the first result on google: http://www.refresh-sf.com/yui/

like image 25
Josh Pearce Avatar answered Oct 21 '22 09:10

Josh Pearce