I've seen alot of jQuery implementations of existent JavaScript functions that merely wrap the JavaScript code in a jQuery wrapper and don't actually rely on any of jQuery's base for their operation.
What are the benefits of using Javascript as a jQuery plugin?
If there are none is there a speed loss to use a jQuery plugin that could have easily been implemented outside the wrapper just as well?
Many thanks in advance (just trying to learn something here).
Updated with example:
http://plugins.jquery.com/project/base64
was originally
http://www.webtoolkit.info/javascript-base64.html
Much of jQuery is just a clever wrapper around existing JavaScript functions. $('#some-element') is perhaps a little easier to type than document.getElementById('some-element') but is otherwise not much different.
(I exaggerate, but only slightly.)
The main utility of jQuery is being able to combine together its various components. If I can select elements with a jQuery selector and then perform some action on those elements directly through a jQuery function, that's preferable to having to extract the underlying DOM elements and manipulate them manually, for example.
So it really depends on what functions you're seeing get wrapped. Some of them might very well add no value, and the authors are simply accustomed to everything being in jQuery. (We definitely see that phenomenon on StackOverflow — people who can't find a standard JavaScript function simply because it's not in the jQuery documentation). In other cases, there might be some hidden benefit even if the wrapper does little if anything to modify the underlying function's behavior.
There's also a lot of momentum around jQuery, and general trust. Including arbitrary javascript in your code base may not be as 'acceptable' to higher-up-types as including a new jQuery plugin.
So it may be a mistaken perception, but by being a jQuery plugin, a library benefits by being associated with high quality code.
IMHO the only reason to create a plugin is to execute some functionality against a selector ie a set of selected elements eg
$('.myelements').someFunction();
If your plugin ends up looking like this (case in point the newly released Microsoft Globalisation plugin)
$.doSomeStuff();
then there isnt much benefit that couldn't be gained from using a closure. However a lot of developers dont understand closures and namespaces in javascript, and by following a plugin development templatethey can get the benefit without fully understanding the pattern.
Related
I'm new to lo-dash, and wanted to know is it possible to use _.bind as $.bind and how can I accomplish this? I really want to get rid of jQuery and use something smaller...
What I need is to bind DOM events to functions
Those are two different mechanisms.
_.bind sets the this value of a function to the first parameter so that 'this' will always point to the same object in the function. I'd say it binds the scope of 'this' to the function, except that would be incorrect technically.
$.bind adds a jquery triggered event listener to a jquery wrapped element.
There are plenty of dom selection alternatives (such as zepto.js), but lodash/underscore libraries are really in addition to jquery, not in lieu of jquery.
That being said, this may not necessarily answer your question, except to say zeptoJs might be one such alternative. Again, Underscore/Lodash is not an alternative to but one or the other provides additional functionality (that in the long term will save file size.)
fwiw imho. 37k is not a valid arguments against jquery/lodash and other such tools. why?
1) If you serve your libraries from a cdn its not even a valid hit against the server.
2) These libraries help you write WAY SMALLER code.
In fact this claim sounds more like an excuse than a reason.
cheers.
I am currently working on a library plugin for jQuery that might eventually be released as an open source project.
I have written a number of custom element functions and would like to store everything related to my library in a namespace.
So for example, assume that I have a function called toggle(). Ordinarily, this would be called using $(selector).toggle(). However, I would like to call it, and other functions using something like $(selector).mylib.toggle() so as not to interfere with other libraries or plugins.
I have developed jQuery plugins in the past, but never needed to protect methods in this way. Can anyone point me in the direction of how I might author the functions to achieve this?
I'm not exactly sure, why you would want to do this and not use an "ordinary" namespace object which holds your methods. However, you might want to have a look at
jQuery.sub()
Description: Creates a new copy of jQuery whose properties and methods
can be modified without affecting the original jQuery object.
By "sub"(classing) the jQuery object, you don't have to care about conflicting with other plugins anymore. So if that is the only concern, go for it.
Ref.: .sub()
I have embarked on a mission to start using jQuery and JavaScript properly. I'm sad to say that historically I have fallen into the class of developer that makes a lot of really terrible mistakes with jQuery (polluting the global namespace, not caching jQuery selectors, and much more fun stuff - some of which I'm sure I have yet to discover).
The fact of the matter is that jQuery allows people to easily implement some really powerful functionality. However, because everything "just works", performance concerns and best practices immediately take a back seat.
As I've been reading articles on JavaScript and jQuery performance and best practices, I've learned just enough to fully realize how inexperienced I really am. I'm left feeling frustrated because I'm unsure of when I should be using jQuery or just plain JavaScript. The main reason jQuery is so appealing to me is that it takes care of browser compatibility. From what I understand though, there are things you can do with jQuery that you can also do with regular JavaScript that aren't subject to compatibility issues. Basically I'm looking for a guide that explains when using jQuery over regular JavaScript is wise.
A few questions to recap:
Are there parts of jQuery that you shouldn't use due to performance?
What are the parts of jQuery that you should always use to avoid browser inconsistencies?
What are the parts of jQuery that you shouldn't use because there is a reliable and faster way to do the same thing natively in JavaScript?
What are the parts of jQuery that offer multiple ways to do the same thing, with one way being more efficient? For example, the :not() selector versus the .not() method.
I'm looking for existing articles, blog posts, books, videos, etc. I know where the docs are. I read them frequently. I'm hoping for more of an overview that addresses the above issues.
Thanks!
EDIT:
Check out this very similar question: When to use Vanilla JavaScript vs. jQuery?
Wow, I simply cannot believe noone has mentioned storing objects in variables for future use.
Consider this scenario.
You have a complex menu that you're going to write 100 lines of jQuery for.
VERY OFTEN I see something like
$(".menu").fadeIn("slow");
$(".menu li").each(bla bla);
$(".menu li").hover(more bla bla);
if($(".menu").attr('id') == 'menu1') {some hoo ha}
If you're going to reuse an element in jQuery, ALWAYS store it in a variable. It's also common practice to add a dollar sign ($) before the variable name to indicate a jQuery object.
var $menu = $(".menu"); // store once and reuse a million times
var $menu_item = $("li", $menu); // same here
$menu.fadeIn("slow");
$menu_item.each(bla bla);
$menu_item.hover(more bla bla);
if($menu.attr('id') == 'menu1') {some hoo ha}
I definitely say
use the event model as it abstracts the differences across browsers and also provides a means to raise your own custom events too.
don't use .each() or $.each() unneccessarily. Sometimes it can help as it introduces a closure, but often a simple loop will suffice.
the only way to know whether a complicated selector string or a bunch of chained function calls is going to be faster is to benchmark all approaches.
use event delegation when binding the same event handler to more than three elements (I'll see if I can dig out the resource for more than three elements, I seem to remember an article that benchmarked direct binding versus delegation on a number of different factors and found more than three to be the magic numbers).
Above all else, don't worry about performance unless it's a problem. 200ms compared to 300ms, who'll know the difference? 200ms compared to 1000ms, maybe time to look at optimizing something :)
be as specific as possible with your selectors and help those poor older versions of IE out.
Several of your questions focus on performance.
As a rule, jQuery cannot possibly perform better than the underlying native Javascript. jQuery does not interact directly with the browser or operating system; it's just providing a wrapper around built-in Javascript functions. So at an absolute minimum calling a jQuery function incurs the overhead of an extra function call.
In many cases, jQuery is indeed doing quite a bit of heavy lifting in order to produce a result, when hand-written "pure" Javascript might be able to avoid that work.
The point of the framework is to make the programmer's life easier, and historically everything that's ever made programmers' lives easier cost performance. Hand-written machine language is almost universally more efficient than the best compiled code ever assembled.
So the best answer to your questions about performance is: don't worry about it. If you ever encounter a performance problem, then consider jQuery as one possible target for optimization.
As far as browser inconsistencies, one of the major purposes of the framework is to avoid them entirely. There have been bugs historically where certain features didn't work in one browser or another, but these were bugs specific to a particular version of the library. So avoiding them entirely wouldn't be quite the right solution. And trying to identify them here (rather than jQuery's own bug reports) would make this discussion almost instantly out of date.
Nowadays, the primary rule of thumb with javascript is that it has wicked-fast execution time (on non-ie modern browsers), but dom access/manipulation is crazy slow. The faster the JS runtimes get, the more the DOM becomes the bottleneck.
As a rule, you shouldn't really overly worry about performance until it becomes an issue, since most code doesn't need to be fast, and you usually don't know where the problems will be until you test it. That being said, try to minimize dom interaction wherever you can.
as a side note, idiomatic jquery is using javascript the right way. Favor composing functions over OOP, use closures for encapsulation, don't mix javascript handlers (or heaven forbid, script blocks) in your html, and treat objects as property bags that you can attach or detach things to at will.
I'm no expert but I learnt a couple of things.
Don't abuse HTML attributes, that means don't store your intended roll-over images in a rel/rev, use a background image instead. This also helps with the performance of roll overs in IE, as IE doesn't like it when you are changing the src attribute on the fly.
Also hover-intent is very useful to have instead of just using .hover :)
My two cents: do not underestimate the power of the jQuery team (Resig an Co.)---their intent is not to lead you easily into performance gotchas. That being said, here's one: when you use a selector (which is the query in jQuery), do insure to use [context].
So let's say you have a table with 243 rows---and you have not tagged each tr with an id (because you are cool). So you click, say, a button in a row with an event. The event for the button needs to search the current row for a select widget. The innards of the click() event might have these lines:
var tr = $(this).closest('tr'); //where $(this) is your button
$('td select', tr).css('color', 'red');
So the last line there does a search for select elements in the context of a table row (tr). This search means to be faster than searching the entire table (or the entire page) for an id or something similar.
What is also implied here is that I'm putting my trust in the jQuery team that their implementation of the jQuery.closest() method is fast and efficient. So far, I've no reason not to have this trust.
What are the top 5-10 most often used jQuery native API functions? (please do not suggest jQuery() function itself as there is no doubt this is the most often used one) If it is possible please also provide scenarious they cover.
The reason to ask this question is my attempt to create a jQuery-like API to the Ample SDK JavaScript GUI Framework (there it is mainly matter of re-pointing functions, thanks to all functionality implementation present). This framework has already standard APIs (DOM Level 2-3), however from what I hear, many developers do not know well DOM APIs, others don't like those APIs, but they like concise API of jQuery (both convinient functions and fluid programming practice)
I find I'm using .val, .attr, .addClass, .removeClass, .hasClass, .hover, .click the most.
.val / .attr / .hasclass I use to identify pre-set values. I usually use custom attributes on elements, and getting them back with attr is great. Like storing if I've already pre-loaded content of an element. The rest is pretty straight forward.
jQuery.ajax and it's equivalents (post, get, etc) are invaluable when making AJAX calls.
DOM read/write functions val and attr are also quite useful, but one of the reasons that jQuery's DOM functions are so useful is not necessarily the functions themselves (other than the fact they are cross-platform) but that jQuery's selectors are such a powerful means of working with the DOM.
I use .animate, .hide and .show a whole lot. Very easy to use and gives the website the little extra if you add values to hide and show :)
There are several different useful jQuery functions that you'll use on many websites. Here is a list of the top 10 and examples of how to implement them: 10 Most Useful jQuery Function For Your Website - WebDeveloperPost.com
There are some things accross these which I'd like to use. I hope they've choosen clever naming conventions to prevent collisions with all their functions and classes? Does anyone use all these at once in one site?
Whilst it can be done (with noConflict), there are still potential conflicts.
For example jQuery adds a unique ID to element nodes it touches, which it expects to manage. If you remove such elements through a means other than jQuery you can get a memory leak; if you clone them from another framework (or DOM calls), you can confuse jQuery with subtle and weird results. There are also many potential interactions between the event models of the frameworks, especially live in jQuery.
If you keep the elements touched by each framework entirely separate, you might be able to get away with it. But really, I wouldn't recommend it. If at all possible, keep the number of frameworks used by your pages between zero and one.
It is possible to use mootools and jquery together, or jquery and prototype together simply by using jQuery.noConflict(). Using all three together might be a stretch as I don't believe that Prototype and Mootools have a no conflict mode and both define $. However, there is this article that talks about using $ safely in Mootools, which might be able to solve your problems.
Mootools and Prototype both extend native javascript objects such as String and Array. I don't think there is any way you can make both of them work together without some conflict.
However, jQuery defines only a single global $ object which it can let go if you use the noConflict mode. You'd then be using the jQuery object.