jQuery - application code vs making a plugin - javascript

When does it make sense to turn your code into a jQuery plugin?
What are the criteria / signs that parts of your code might be better as plugins?

Actually, your code is a jQuery plugin as soon as you start adding new stuff to $.fn.
But besides that, it makes sense for reusable code or code which is not specific to your application.
Also have a look at the Plugin Authoring Guide - it shows you some best-practices you should follow; especially if you might release your jquery plugin at some point. But it might also give you some ideas about when it makes sense to make your code a plugin.

It is more than anything a matter of if the code is at all abstrable/reusable at all and if so, if you think you will actually need to be reusing it at any point in the near future. I generally end up with a mixture of both; common functionality abstracted into plugins, and page-specific custom code intializing those plugins and setting up whatever is unique to that page.
I know exactly what you mean about where to make the decision to abstract it and there are no hard and fast rules to follow. If it isn't completely obvious, you can at least try to write the custom code with an eye to the future that you might be making it into a plugin. Javascript really makes that easy with its closures.

Related

Extend Zepto.js so don't need jQuery anymore

I like the idea of cutting out 80% of jQuery by using Zepto.js. However, when making the switch, it is clear some of the jQuery plugins I'm using, for example jQueryUI draggable(), can't find in Zepto what they need.
Is there a sane way to go about switching to Zepto? Or Am I just going to have to extend it function by function until I stop getting errors?
Hear me out. In a perfect world we always have frameworks that are exactly what we need. But we don't live in such a world. Different projects - different requirements. JQuery is designed to cover ALL of the usual requirements, therefore saving time. It may sound tempting to try to optimize it for the project needs, but in the wrong run, will it be worth building frameworks for every small project? In the end it's only 15 kbs of difference, a fraction of a second. As javascript is not compiled you don't save from compilation-time or anything. Just that little tiny bit of bandwidth. I'm not aware of the importance of your project, but I personally wouldn't sacrifice my time to build a custom jQuery distribution for every new project I'm creating.
If the stripped down Zepto doesn't work out, I'd stick with jQuery. But if you are determined to do this, I think it would be easier to start striping jQuery down, instead of upgrading Zepto. That way you can instantly tell when your modules break and see the reason.

Is it a good idea to write jQuery plugins just for the sake of neat code?

For example if you write a plugin you could do this $('#myDiv').doAction() instead of doAction($('#myDiv')). and you have to admit, the first one looks more intuitive. Are there any clear drawbacks of this like performance hits?
You won't see any noticeable performance hit from this, but there is one potential drawback: namespacing your code is very valuable, and makes it easier to maintain (as you probably know). Throwing everything into jQuery.fn may not be the best way to do this.
Personally, I shy away from extending jQuery with very specific things (like app-specific logic or something) but whole-heartedly recommend it for general, DOM-level things (.hasAttr() and .scrollHeight() are two I use a lot). The reason is that there are better places to put app-specific logic (in the module in charge of that area of the app, for example).
A simple heuristic: would it be useful to other people if I made this a public extension? Or is this only relevant to this particular project?
That said, there is no concrete problem with doing this in your code. It's more a semantic issue: is that the best place for it?
Write a jQuery plugin so that you do not need to repeat this over and over again.
There are literally minimal performance issue with this, and mindful that this is at client side, it does not attribute to your server resources.
There aren't any performance hits choosing one approach over the other. It's more of a question of, do you need it as a jquery plugin? I create regular functions if it's a utility function and doesn't need to act upon a jquery object. If it does, then it should be a plugin (no need to pass in the jquery object as a parameter, and you can chain)
You seem to be using jQuery as a framework. It is not one.
Please use a client-side MVC style library like backbone/knockout/sammy/eyeballs for seperations of concerns and structure
Please use an AMD loader like curl/requirejs for modularisation of your code.

Wanted: Minimal cross-browser Javascript library

I know some Javascript, but just realized I know very little about cross-browser issues. Nasty little things like the this object in event callbacks in IE (as in xhr.onreadystatechange = function () { ... }) not referring to the object the function is applied to, but instead to window, which is not exactly useful.
There's an impressive and comprehensive-looking list of differences here on SO.
Is there also a library that covers these nasty cross-browser issues without selling you a whole lifestyle plus round corners with slide effects? I know jQuery is great (and modular, I know, UI coming as an extra; and I bet others are great, too), but I'm looking for something lean, closer to the roots. Just doing the minimum and eliminating the nastiness. Doesn't have to wrap the DOM in sugar.
Update
Thanks everybody for your suggestions. I'm going to take a look at MyLib, microJS, Ender, and Sizzle. GWT, while certainly being cross-browser, is not, I think, a lightweight approach, but definitely an interesting one.
jQuery is not modular - it's all or nothing. If you want a solid, cross browser library that you can trim to the minimum you require, it's hard to go past MyLibrary: http://www.cinsoft.net/mylib.html.
The name "MyLibrary" means that when you download and customise it, it becomes your library.
It is absolutely solid, fast and extremely modular. You can use just the bits you want and remove anything unnecessary.
BTW, many libraries like jQuery aren't really "cross browser", they are multi–browser — they have a limited set of browsers that they support and don't care much about the rest. On the other hand, MyLibrary is written to be genuinely cross–browser. It also provides excellent feature detection shortcuts so you can easily write robust code with fallback.
What do you want?
Just check microJS and download the libraries you want.
As mentioned already you can use Ender to bundle them
"Minimal cross-browser Javascript library" + "I'm looking for something lean, closer to the roots"
I immediately thought of MyLib.
You can even build your own custom version using this online tool.
I think you should have a look at Ender By Dustian Diaz and Jacob Thornton working at Twitter.
Ender is not a JavaScript library in the traditional sense. So don't
rush out and try to replace jQuery or MooTools with Ender... It just
wouldn't work.... But! you can build a library from Ender which will.
And you should. right now.
That's because: Ender is an open, powerful, micro-to-macro API for
composing your own custom JavaScript library; it wraps up application
agnostic, independent modules into a slick, intuitive, and familiar
interface so you don't have to.
Well the problem with this in JavaScript is that it can be a bit confusing to people which are not accustomed to the fact that it always gets a contextual value or in other words it will always point to the object which is in the current context of the executing code.
In case of some events, intervals etc. its absolutely normal that this points to window because a LOT (perhaps too much) of properties in JavaScript are attached to the window object.
As for which JS library to use for your work...Well if you don't want to use jQuery as a whole there is always the most important part of it which handles selection of objects inside DOM and is pretty much important for cross browser compatibility.
Its called Sizzle and can be found here. It doesn't offer fancy stuff like jQuery does but it is small and offers a great cross-browser way to select stuff on pages.
You can look at GWT.. but it does sell you a lifestyle as well - a Java dev environment. But that also brings in a debugger, a proper IDE, easier OO, it compiles to optimized cross-browser javascript etc. And you can always mix and match native JavaScript where you see fit.

Overusing jquery

When using a javascript framework such as jquery, is there a realy chance of overusing the library for things that can be done simple using plain old javascript.
If so, then does this type of thing:
A: Slow code down
B: Make code less portable
C: Make the programmer less knwoledgeable about what is actually going on underneath everything
Im thinking of things like using jquery .each instead of a simple for loop. Sure this adds a bit of code but then its 'real' javascript if you get what i mean.
Maybe im just being naive.
Well, I suppose there's a chance, but in general the advantages far outweight the disadvantages.
In general
a) it may slow code down slightly if you're doing something that wopuld be simple in pure JS, but in most cases that';s been optimized in jQuery anyway. On the other hand, the naive way you'd do much of anything complicated is probably not as fast as Reisig et al will have done it.
b) It certainly makes code less portable in the sense that it's going to depend on the jQuery libraries. On the other hand, it will be more portable across browsers and versions, which is the more important consideration.
c) yes, it may conceal some of the javascript magic. My experience, however, is that you eventually have to learn it anyway; in the mean time jQuery makes you much more productive, much faster.
(Note, also, that these points actually apply to most libraries. jQuery is my favorite, but I write a lot with dojo, and have used prototype, scriptaculous, and YUI happily.)
B) it makes code more portable, not less, because differences between browsers are handled by the framework implementation.
AS for slowness, I would think that the initial load of jQuery would tackle most of your functionality. If you are loading 20 plugins then you may run into some issues.
jQuery is no less protable than any other JS file. Even less so if you are using a CDN.
I do tend to agree with the third point. I tend to not fuss with much actual JS anymore I just use jQuery to do everything, within reason.
Overall, I think jQuery and other JS lib's are one of the best things to happen to web development in the last bit.
The really great thing about jquery is they have already come up with some quick, smooth code that helps to protect you from cross-browser hazards. So, I am sure anything can be abused, but the benefits of knowing that my code is more likely to keep up with future browser changes simply by updating jquery's API without worrying about your my outdated javascript code gives me a little more peace-of-mind. Is it perfect? Noooooo. But right now, it makes my life sooooo much easier both now and in the foreseable future. If you write "raw" javascript-only code, then if one single browser changes the way they handle your situation, then that is one less segment of users that can efficiently view your site.
I figure if I'm going to load a library on a page, I may as well use it as much as I can. I try to get the bang for my buck (so to speak).
Of course, like any "new" technology, it is overused.
It's the same for things like Linq or CSS adapters for .NET.
The rule is if you can make it simple and efficient, do it!

New to javascript, why is jQuery such a beast?

I'm new to javascript (functional programming is okay for me, though) and I am wondering how jQuery got away with some of the design decisions they made. Is it just too much work to fix now or what? For instance, there seems use of strange symbols in strings when accessing elements in the DOM or weird function definitions for $, that are forcing me to check references every other time I want to get some basic data.
Can someone point me to a learning source where I can learn all of these nuances of jQuery (jQuery's examples just don't cut it, they're too spread out)? Maybe someone has a super good reference site/pdf for jQuery?
Thanks
EDIT:
And as a side point, in regards for learning, why the heck is the entire jquery.js file collapsed onto a single line? It is unreadable.
Try reading jQuery in Action, it's a really good book to get started with jQuery. Next to that you can also watch examples on jquery.com, but I did prefer the book to get started.
For JavaScript basics you can try w3schools.
In the beginning I had the same problem with the $ functions etc, but after I read the book it became all clear to me, and to be honest, I wouldn't use plain JavaScript without jQuery anymore for DOM manipulation.
For your edit: you have a compressed (or minified) version, which has all code on 1 line, most spaces removed etc to keep it small and a readable version. Both files can be found on the download page from jQuery.
The strange symbols you refer to are mostly CSS selectors, the standard way to address elements on the web. jQuery could've come up with its own conventions, but decided to go with what was standard and best known.
jQuery itself is surprisingly consistent. Once you wrap your head around the jQuery style you barely have to consult the documentation; things just work as you'd think they should.
The jQuery documentation is actually quite good and includes an example with every command. It also has a large user base, so a quick search will generally answer any questions you have. Google is your friend.
I'm guessing the issue is not jQuery, but a difference in javascript style compared to languages you're more familiar with. Watch Crockford's "Javascript: The Good Parts" for a reasonable introduction to good javascript style.
http://video.yahoo.com/watch/630959/2974197
Also check out Dustin Diaz's posts, I found his early screencasts where he'd build an app and talk about what he was doing very educational:
http://www.dustindiaz.com/
I think jqapi.com is a more useful jQuery API documentation resource than jquery.com
Compressed javascript uses less bandwidth to load up, and decreases load times. Use js beautifier to expand it.
jQuery is the greatest thing to happen to the DOM API, which is just awful to deal with. It also handles cross-browser issues and older versions, giving them functionality they otherwise wouldn't have.
The strange symbols in selectors are from CSS, not the fault of jQuery. The selectors API is now being built into browsers, so it's worth it to understand what they mean.
As for a functional programmer every imperative language is probably a failure in your eyes and mindbending to capture, with javascript and jquery probably on top of that list. They both have side effects all over. Jquery is really about manipulating the DOM so the side effects are the means and the goal, as opposed to proper functional programming.
If you're young enough you can still make the mind switch though :-)
start on jQuery Docs Main page...
You could try some other JavaScript frameworks to find out which one suits you best.
Although jQuery is pretty cool for most people, it's not the holy grail for everyone.
Maybe it's just not "your thing".

Categories