tags:

views:

178

answers:

5

I'm using just a few basic jQuery functions on my site.
How can I remove unused jQuery code?
Knowing only the basics, I looked at the code and was not sure where to start. If you could point me in the right direction, that would be appreciated.

Thanks.

+3  A: 

The question is - why? Production version of jQuery 1.4.2 is only 24Kb. With proper cache control of the file, it will be downloaded only once and cached. Why bother?

Strelok
Expensive internet taxes, you know.
jweyrich
Strelokstrelok, while being absolutely correct, you're not answering Tommy's question - which is both fair and simple.
Már Örlygsson
+11  A: 

jQuery itself isn't really built to be selectively used. There are lots of interdependencies between its own functions and the source isn't laid out to be easy to modularise. Unlike the situation with plugins like jQuery-UI, the core of jQuery is pretty much take-it-or-leave-it.

If you've only used a few simple functions, you might be able to rewrite them in plain JavaScript. If the main function you're using is selectors you can use Sizzle, which is the underlying selector library that jQuery itself uses. Otherwise... not really.

bobince
It's worth pointing out, that this sort of modularity is one of the key goals of the next major version of jQuery - to make the library scale down better, by allowing developers to specify (roughly) which parts of the jQuery they need and skip the rest.
Már Örlygsson
+3  A: 

If you want to further reduce the code size, minify and gzip or deflate it. Beware that gzipped code needs to be uncompressed before it's executed, thus causing a delay. The jQuery download page offers an already minified and gzipped version.

Another option you could look into is using CND hosted jQuery, that is jQuery hosted by third party organizations such as Google or Microsoft. Details in the jQuery download page.

Cesar
Good note - googles ajax libs! Upvote.
Glycerine
just replace "gzip" with "deflate" and I'd agree. See [this](http://stackoverflow.com/questions/1574168/deflate-compression-browser-compatibility-and-advantages-over-gzip)
David Murdoch
I wasn't aware of the advantages of deflate over gzip. Thanks!
Cesar
A: 

additionally you can minify the resulting jQuery library to condense it by roughly 55% (googles complier app) with destroying the code. although I do agree with @strelokstrelok - its an unessasery step as the odd advert on your page would have a larger filesize.

Glycerine
+2  A: 

As others have mentioned, you don't need to do this.

If you're concerned about bandwidth, you can reference jQuery from Google's AJAX API, like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js"&gt;&lt;/script&gt;

To answer the question, that would be extremely difficult.

As you've noticed, jQuery is written in a very terse and efficient manner, and does not have easily removable chunks.

SLaks