0

I have several JavaScript files that I need to bundle and minify manually. We can't use the standard System.Web.Optimization bundles on application start solution as it causes issues due to our complex caching needs.

To bundle and minify these, could I just concatenate the file content, then minify using a simple processor like System.Web.Optimization.JsMinify? Would there be certain types of JS code for which this method wouldn't work?

andrewb
  • 5,200
  • 6
  • 36
  • 54
  • i think it's a bad idea for two reasons: 1. some files end in "}()", which if concat'd by a "(function(){" causes a syntax error (inserting a semi between fixes this). 2 is worse: an unexpected "use strict" on any of the script's behalf can break the whole stack, or just some scripts in it. if you can guard against those, a concat before shrinking _usually_ produces leaner output that compressing them separately. – dandavis Aug 25 '14 at 02:47
  • @dandavis Isn't the answer simply to write correct JavaScript? – andrewb Aug 25 '14 at 04:22
  • 1
    a lot of time we don't write the files, and we don't want to fork or fix each depends we bundle, and some of them, especially ones shrunk with uglify/closure don't always stack up nice. we also can't control how includes implement "use strict", other than by going all-in and hoping the browser supports it... – dandavis Aug 25 '14 at 05:18

1 Answers1

1

Everything that is pure javascript (ie you're not concatenating something like coffeescript to a javascript file), and is closed off correctly should concatenate fine. The order that you concatenate the files is important, it should be the same order as your current order for synchronously loaded scripts.

Code not closed off correctly:

file1.js

var ten = 10;
var twenty = 

file2.js

$(document).ready(function() {
    // Do stuff
});

If these files are seperate, file1 will throw an error, but file 2 will run correctly. If you concatenate them:

var ten = 10;
var twenty = 

$(document).ready(function() {
    // Do stuff
});

The error will be thrown and the document ready statements will not be executed. Hopefully there isn't something like that in your code, but you never know.

andrewb
  • 5,200
  • 6
  • 36
  • 54
James Hay
  • 7,115
  • 6
  • 33
  • 57
  • What do you mean by "closed off correctly" - having (function() { // code })(); around code which relies on local variables? – andrewb Aug 25 '14 at 02:23
  • That's a good way to do that, but what I really mean is not having any open code at the end of your file that will throw an error. I'll add an example... – James Hay Aug 25 '14 at 02:24