views:

65

answers:

2

How do I use Google Closure compiler to remove unused code?

I am using the JQuery Slider control but am not using anything else within JQuery. So I read that Google Closure compiler in Advanced mode can remove unused code, but I don't know how.

I have frontpage.html that links to an external JQuery, JQuery UI and JQuery Slider control from that html page hosted on my site.

On my frontpage.html, I also have JavaScript embedded within the HTML that initiates the JQuery Slider control.

How do I use I use the online Closure Compiler to evaluate my frontpage.html, JQuery, JQuery UI, and JQuery Slider to remove all of the unused JQuery code that I don't use?

+1  A: 

First as a beginner I suggest you try simple optimization. Because it works without any configuration and yields great results. Don't be mislead by the name. Simple optimization offers better savings than any other compression tool out there. Advanced level can be your next step but it's a little more complicated.

As for using the compiler. My advice is to pack all your scripts into one javascript file, upload it to your website so it will have an url, pass it to the online complier. Then you click Add and Compile and you're done.

In the right hand side the compiled code you'll see. Also a file named default.js will be created and you can downloaded.

Next step is to rename it to your needs, then upload to your server, change the .js reference in the HTML and you're pretty much done. Have fun!

galambalazs
A: 

There are two ways to remove/exclude unused code from your combined output script:

  • The first, involves using ADVANCED_OPTIMIZATIONS compilation level (refer to Advanced Compilation and Externs for detailed explanation and usage)
  • The second, is to allow the compiler to manage dependencies (i.e. using the --manage_closure_dependencies compilation flag

Of the two options, using the --manage_closure_dependencies flag to remove unused code is less granular (i.e. excludes code at a file level), but it does allow you to remain at SIMPLE_OPTIMIZATIONS compilation level. In either case, you will have to include the url to jQuery and jQueryUI scripts and your code that consumes the jQuery Slider from your page-something like this (1st option):

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @code_url http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js
// @code_url http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.js
// ==/ClosureCompiler==

// ADD YOUR CODE HERE

Hope this helps.

HOCA