5

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?

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Steven
  • 19,224
  • 47
  • 152
  • 257

3 Answers3

6

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.

nicholaides
  • 19,211
  • 12
  • 66
  • 82
  • You are a life saver man! I wonder: Why some scripts do not follow this practice? Why we must edit their source code to simply add a semicolon? – nik_m Nov 07 '16 at 18:56
  • @nik_m. I wonder why all concatenating tools don't add this for you. – nicholaides Dec 04 '16 at 21:14
3

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

Josh Pearce
  • 3,399
  • 1
  • 23
  • 24
  • Thanks that worked. Obfuscating the code afterwards kind of kills the compression though :( – Steven Nov 17 '09 at 03:07
  • I tested obfuscating using this site: http://www.javascriptobfuscator.com/Default.aspx – Steven Nov 17 '09 at 03:08
  • Even if you're using YUI compressor, you can run into this problem, as I did. See my answer about semicolons. Changing the tool you're using might just be rearranging the files and will hide this problem, but it could crop up again next time you run YUI compressor. – nicholaides Nov 17 '09 at 03:09
0

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:

(function($) {
$.fn.defaultInputs = function(settings) { ...

i have simplified to

jQuery.fn.defaultInputs = function(settings) { ...
Davincho
  • 121
  • 1
  • 7