I know questions around javascript compression have been asked multiple times but I cannot find any answering my problem.
I have a project that has common scripts (jQuery and a few others) and page specific ones. jQuery Mobile allows you to cache common scripts during a session by downloading anything that is in <head> only once. The specific scripts are pulled only if the page is loaded as long as you put the <script> in the <div data-role="page">.
I find this great because it optimizes scripts that are downloaded while browsing the pages of my app and ensures the browser has the minimum javascript in memory at any time.
However, it is terrible for minification because there are dependencies between various files that cannot be merged.
So far I found two solutions that do not suit me so well:
- using a simple minification script that does not change function and variable names: it doubles the size of the files compared to an advanced version
- grouping all the scripts into one and compress it then put it in the
<head>: you lose the ability to only download the scripts you may want and the browser has unnecessary functions loaded
(I exclude manually changing the function names obviously 😉 )
I am looking for a compressor that could do one of those:
- compress all the files together but output them into seperate files to keep the modularity
- if not possible, compress files independently in an advanced way but with tags that could prevent the minifier from renaming links to external functions or variables (such as jQuery ones)
Does it exist?
After getting more familiar with all this, Google Closure Compiler can do that (and much more).
The way to go is to define externs for:
Obviously, if you compress the home made scripts that are loaded separately, you should export the variables you want to use elsewhere using the following technique (detailed in Closure Compiler documentation) :
Then you can compress files you want in batches or separately. It is such a powerful tool that I cannot believe I did not use it before.