Ripping JQuery from unnecessary/unused pieces: is this possible? - javascript

Is it possible to ONLY use portions of JQuery, just like with JQuery UI: customize ones own build in an easy way?
What i mean is imagine you ONLY need JQuery library for a silly, tiny but handy tool on youw site, lets say the Dialog boxes.
Are there JQuery builts available specifically supporting portions of functionality, at a fraction of the current Javascript code sizes?

If you only need a tiny portion of jQuery on your site, chances are good you don't need jQuery. Have you considered a smaller library such as underscore or head.js? Is there something particular about jQuery that you need that can't either be handwritten or found in a smaller library?
The minified version of jQuery is 82kb, and for speed's sake can be hosted on google's CDN. Check out the CDN Hosted jQuery section of this page: http://docs.jquery.com/Downloading_jQuery

You need to think of it from the opposite angle. What you need is dead-code removal (i.e. remove things not used), not "include things that are used."
The only popular dead-code removal processor I know of is the Closure Compiler's Advanced Mode. Beware I am NOT talking about Simple Mode, which only does minification and not dead-code removal nor any other optimizations.
jQuery, unfortunately, is not (yet) compatible with the Closure Compiler's Advanced Mode.
However, you can consider the Dojo Toolkit, which is compatible with Advanced Mode after certain modifications. Read it here.
If you want to use a popular JavaScript library, but don't want to include everything, you can look into Dojo.
A Dojo application with only very light usage of the Core functions, after compiling with Advanced Mode, can be reduced to less than 40% of the size of a only-minified version (e.g. Closure Simple Mode).

Not that I know of. Except for css based selector which is sizzle incorporated into jQuery. But I am sure you can write or find pure js library that has only the functionality you need and skip jQuery if you really want to.

You can have at jQuery in pieces: https://github.com/mythz/jquip
It is unofficial, though.

You could feed jQuery plus all of your code through the Closure Compiler; that would remove everything you weren't actually using. I don't know how much smaller it would get, though; it might be all interdependent on the inside.

Related

Partial JQuery library, tailored for each project requirement?

The JQuery let's you do all that wonderful stuff, while taking care of browser difference and maintaining a smooth language.
But what if I don't need all of this ..
Maybe all what I need is just the ajax call (that what most of really want anyway) and I don't want to pay the cost 90+K library just for that feature alone "or with a couple of other features"
Is there a way to "extract" the options you mainly need from JQuery?!
Something similar to what modernizer are doing? See here: http://modernizr.com/download/
Don't get me wrong here, I'm still a "lazy dev" who wouldn't like to reinvent the wheel & care about different browsers compatibility etc. .. so I still want to use a library .. but just tailored for my needs.
RobG pointed out the existence of MyLibrary which have a builder to deliver what I "only" need. Checking it out & it looks very cool. will certainly try it.
You can get an unminified copy of the jQuery source and remove the methods you don't need. Just be careful with removing methods that AJAX might have dependencies on.
For those developers who aren't "lazy dev"s, getting examples of what you are trying to do from the source of any open source libraries and forming your own modules is a great way to go.
There are resources out there to get you to just snippets you need such as Micro.js and james padolsey's jquery source viewer.
Once you have build a nice set of modules and established what dependencies you have internally, you can create min files specific to a page or portion of a project and cutting out all of the extra weight you don't need
This is can be the answer to the question regarding how to extract jquery needed part(s)
http://projects.jga.me/jquery-builder/
it divides the library (v1.10.2) to
ajax, css, deprecated($.uaMatch, $.browser, $.sub), dimensions , effects , event-alias , offset & wrap.
But for the purpose of the question, which is not paying that much valuable kilobytes over the precious network... it turn out that, using this builder, cutting everything only reduce the filesize by only 30% ...
so :) practical solution (till the moment) remains the same 1- not using jquery (use your or another library) or 2- accept the price of those 90k

Are shared libraries with AMD a good idea?

I'm fairly new to JS development and trying to figure out some best practices for developing and using AMD libraries. Suppose I'm developing a javascript library which depends on jquery, underscore, and whatever else. Furthermore I want to make this library an AMD module and optimize it into a big monolithic file. But the question is, how monolithic? Should it also pull in jquery and underscore so that it's completely self-contained? It seems like the pros and cons of this approach are:
Pro: it's easy to use
as an app developer using this library you can just get it and add a dependency on it, without needing to know that you need jquery, underscore, etc
no having to configure requirejs with the paths to those things
no worrying about the case where one library needs jquery 1.x while another library needs 2.x
Con: it's bloated
if the main application or another library also needs to use jquery, which seems likely, it will essentially get downloaded twice (or n times)
Anything I'm missing here? So which is the right way to do this, or is the answer "it depends", or "make versions of both"? It seems like in general you'd like to share code where possible, but it puts the onus on the consumer of libraries which have non-included dependencies, and necessitates a tool which solves the constraints to find a version of a given library which is compatible with all dependent components. Is there something out there that does something like this?
I can't think of any good reason to include a third party library (such as jQuery or Underscore) with your own library. It's rare to see this technique employed anywhere, if at all, as it restricts the consumer of your code too much.
Not only would it add bloat as you say, but what if I wanted to use Zepto or Lo Dash, or a different version of jQuery? If your library simply lists jQuery and Underscore as a dependency then I could easily map those to load alternate versions or libraries.
Users of AMD (and RequireJS) are typically very comfortable with configuring paths, maps and shims as it necessary in nearly all instances, so I wouldn't worry about that.
Keeping everything separate will also allow flexibility when it comes to optimising the JS for production. For example, I often like the build jQuery into a main module that is loaded on all pages and set other modules to exclude it.
An example of what I mean with that can be seen here:
https://github.com/simonsmith/modular-html-requirejs
I would say you should provide an unoptimized version and an optimized one. If for some reason you can't do both then just provide the unoptimized version. Why the unoptimized version?
Your code is probably not bug-free. It is easier for someone using your library to track down a bug and maybe contribute a patch if there is a 1-for-1 mapping between the original source and what they observed in their debugging environment. (I've tried source maps. They were useful but produced funky results.)
You've said it yourself: libraries like jQuery could end up being loaded n times in the final application. If you provide a way to let the developers use just your library, they can run tests to determine whether they can replace different versions of jquery with just one. (The majority of cases where a library mentions or ships a specific version of jQuery, it's just because it happened to be the version that was current when the library was made, and not because of a hard dependency.)
Provide the optimized version so that someone who just wants to try our library can do it fast.
You ask:
It seems like in general you'd like to share code where possible, but it puts the onus on the consumer of libraries which have non-included dependencies, and necessitates a tool which solves the constraints to find a version of a given library which is compatible with all dependent components. Is there something out there that does something like this?
Yes. A test suite. As a consumer of libraries, I'm unlikely to use one that does not have a substantial test suite. As a producer of software, I don't produce software without a substantial test suite. As I've said above, most often a library that depends on something like jQuery or underscore or what-have-you will list whatever version that happened to be around when the library was developed.

Is there any jQuery build available that's optimized for use with underscore.js?

I'm using jQuery and underscore.js for my personal project and I love both frameworks. The problem is that they heavily overlap at functionality.
For example there are $.each and _.each, $.extend and _.extend, $.isArray and _.isArray and so on. It doesn't really make sense to have all of those methods twice so I'm looking for a jQuery version without those methods.
Is there any jQuery build available for this?
I rather want those methods at the underscore object than the jQuery object due semantics, (jQuery for DOM, AJAX etc. and Underscore for helper functions), but I would also be very happy with an optimized underscore.js version!
jQuery uses those methods all over the place inside its own code. (sometimes with special undocumented behaviors)
You won't be able to remove them easily.
Don't worry about it; the code duplication isn't so bad, and it's much better than maintaining a custom version of jQuery.
You might have some luck trying out JQuip. The project's goal is to develop a smaller, more modular jQuery. Check out their library builder where you can pick and choose what you need and leave out what you don't.
I'm not sure about your project needs, but it sounds like you're supplementing underscore.js with jQuery. jQuip might help by reducing the bloat you otherwise wouldn't need from jQuery.
Good luck!
I wouldn't worry about the code overlap, especially if you utlize google jquery hosting, your visitor/user might already have it cached and it will not matter much in the grand scheme of it all.
I can't see a point of keeping a library up to date to reduce overlap of this nature.
You can consider using http://sizzlejs.com/, which is JQuery's selector engine. You're not gonna get all of the DOM manipulation stuff, nor AJAX.
Also, I haven't personally tried it; but EnderJS looks promising.

compatibility when using the mootools library in a widget?

i want to use the mootools library to do animation & ajax in a widget i'm building.
i plan to have the widget write itself into the page so the end user just deploys a single line of javascript.
i'm concerned about the compatibility issues that may arise if my widget is used on a page which is already using another library.
short tests show problems even when enclosed in a self executing function if scriptaculous is already loaded, although jquery doesn't seem to cause a problem.
what is the best solution to this?
is there any way to load mootools in isolation so i can just use it for my purposes?
i see that jquery, whilst unfamiliar to me, is highly namespaced and therefore probably more appropriate to the task, would using that instead alleviate any potential problems?
can i just copy and paste mootools into my self executing function?
nb: the following error when using with prototype comes as a result of using mootool's setStyle method.
element.style is undefined
element.style.cssText += ';' + styles;
There isn't a method to use mootools. The developers have specifically stated that they are not going to namespace mootools to run along side prototype and they squash any attempts to have the core changed to do it (see 1).
You really are just better off using either jQuery or another namespaced library (I believe both Dojo and YUI are, but I could be mistaken), or if you don't need the overhead, just build your own in good old-fashion JS.
https://mootools.lighthouseapp.com/projects/2706/tickets/219-mootools-namespace
you cannot "namespace" mootools. it is a prototypical library. you seem to indicate that you are trying to use it in conjunction with prototype - which is STILL a prototypical library as of time of writing (there has been talk of them moving away from that).
basically 2 such frameworks alongside of each other will have completely unpredictable results, there are no guarantees on what library's method will take precedence on any of the prototypes that they change.
mootools can co-exist happily with jquery or any other lib that is functional. it also looks for anything already defining $ and if unavailable (say, because $ === jQuery), it reverts back to using document.id() instead.
if your page already uses scriptaculous, then you should do the effects using that (in an ideal world). next-best-thing, you can try jquery but that's nasty for the sake of a simple widget (or any 2 frameworks)
btw, the AddThis widgets used to contain mootools a while back and it did not break any pages it got embedded on so I suppose it is doable. regretfully for you, they seem to have moved to their own vanilla lib now...

How to achieve library-agnosticism when building a javascript framework?

I've started looking into architecturing a javascript framework.
I don't want to reinvent the wheel here, especially regarding browser quirks, and know that for that matter, I'll have to rely, at some point, on some commonly-used libraries to handle low-level concerns.
The thing is, I'm not sure how i can depend on an external library for some piece of functionality (say for example dom manipulation), without tying it to my design.
Practical examples would help make a better point, but I'm not at the design stage yet, and I'm merely trying to avoid getting started on the wrong foot.
So I'm looking for some examples, guidelines, best-practices or maybe patterns that could help in this situation.
Any insight ?
EDIT : Bit of a clarification on why I'd want to do this.
My goal is to build something resembling more of an application framework than most traditional libraries like jQuery.
Think layered architecture, where the libraries would fit into the infrastructure layer (as per Evans' definition in Domain Driven Design), and handle things such as events, dom traversing and manipulation etc...
This is a very broad question, but if I were you, I would use jQuery as a base. It is a very easy library to extend and add functionality too.
I'd recommend grabbing a copy of ExtJS and taking a look at how they provide support for replacing the underlying core of their product. You can use their higher level libraries, such as grids, trees, etc, but choose to use YUI or prototype in place of their Ext core.
That should give you a good starting point.
Edit to answer comment:
Once you've downloaded ExtJS, take a look in the "adapter" folder. In there, you'll see the various adapters that exist to make ExtJS work with other libraries. You'll quickly see how they define functions that in turn make use of the appropriate underlying lib.
Segregate your code:
use the external libraries to the fullest possible, within their separate section of code.
Taking jQuery as an example, just designate a section for interfacing with jQuery and then use jQuery within that section of the library like there's no tomorrow, and give it interface functions that the rest of the code uses exclusively.
Frankly, if you integrate a library with your code and try to make it generic enough that you can trivially swap it out with something else, you're probably going to neuter the library to the point where you might as well have not included it at all.
Accept that you may need to rewrite if you end up swapping libraries, but prepare for that by giving the library-interfacing code it's own separate section, and you'll be able to write less generic, more powerful code with those external libraries and save yourself a lot of work.
This doesn't answer your pattern question, but a word about the frameworks. All of the modern JavaScript libraries are pretty good at playing well with each other, but some are better than others. Just make sure that they libraries don't monkey-patch the core objects with arbitrary properties or muck with the global namespace and you should be good to go. JQuery and YUI are both well designed and namespaced libraries. Dojo is also quite good, but a couple years ago when looking at all of the options, it seemed like Dojo encouraged the use of proprietary element attributes in markup as JS hooks. At that time Prototype was the library that mucked with objects like String/Array and didn't play well with others. I haven't looked/used Dojo or Prototype so take that with a grain of salt. I'm actively using YUI and JQuery in the same app; YUI for widgets and event management and JQuery for Selector/DOM manipulation.
I'd suggest you pick a single general purpose library or no library at all, depending on the requirements of the framework you plan to write. It's very difficult to make any kind of recommendation without more information, such as what your framework is aiming to achieve, who will be using it and in what kind of environment.
If you're considering writing a script of reasonable complexity then I would suggest learning the relevant "low level" DOM manipulation techniques for yourself. It's not as difficult as devotees of some of the famous general purpose libraries would have you believe.
Use some kind of interface to link to the library.
Don't do:
$("blah").something();
do
something("blah")
function something(id){
$(id).something();
}
Since you could call something() 20 times, it'll be simpler to update if the actual use of the library is in only 1 place.
It'll add development time and then complexity, but you won't be as dependent on a library.
I don't think this can be achieved very effortlessly. If you really want this behavior, I think you'd have to manually map the features that are covered by all libraries you want to include support for.
So that the implementation would look like:
yourLibrary.coreFramework = 'prototype';
yourLibrary.doStuff();
And your librar would treat it in the following manner:
function doStuff() {
var elem = getElement('id');
// do stuff with 'elem';
}
function getElement(id) {
switch(this.coreFramework) {
case 'prototype': return $(id);
case 'jquery': return $('#'+id);
/* etc */
}
}
Check out the jQuery or prototype frameworks.
If you decide you need to, then extend these.

Categories

Resources