is using the $() shortcut in jQuery bad practice? - javascript

I was recently listening to a podcast which made a comment on using $() vs using jQuery(). It was stated that every time $() was used a new object would be created and when jQuery() was used this was not the case. I google'd around but couldn't find anything on this specific topic.
I realize this is not a typical example, but the following is the reason I am interested in the answer to this question.
I have a page that the user will keep loaded in a browser for a whole day (24 hours, or possibly longer) and updates are done to the DOM every ~5 seconds as the result of an AJAX call via jQuery (the AJAX call portion is irrelevant to updating the DOM - the update to the DOM is done using a string of HTML and a call on a jQuery object to .empty() and then .html()).
Since hearing this, I subsequently switched all of the $() calls to jQuery() calls, but I would like to know:
Is using $() vs using jQuery() a bad practice? Is there a negligible difference between the two? Or is it actually noticeable on larger projects?

No, it's not bad practice, and there is no performance difference.
The $ and jQuery identifiers refer to the same function instance.
This is done by the last line of jQuery.js:
window.jQuery = window.$ = jQuery;

The only problem with using $() over jQuery() is the possibility that another Javascript framework uses it as well.

Nope - take a look at the jQuery source code. $ is just another alias for jQuery - the last line says it all:
window.jQuery = window.$ = jQuery;
See here for yourself:
http://code.jquery.com/jquery-latest.js

To me, the goal is to avoid naming collision with other libraries that also use $ as main object, like Prototype, if you want to use both libraries on the same page, or you don't know where your code will be used...

Are you sure it was $() vs jQuery()? Maybe the more salient point is that there are performance hits to doing either, and many new js coders use $() unnecessarily when plain js could do.
It's good practice to avoid creating a jQuery object when you don't have to.

As stated before, the only real problem is getting into conflict with other js frameworks used, therefore i find this is the most handy solution to be still able to use the dollar sign, but have no conflicts and make your code more portable:
(function($) { /* some code that uses $ */ })(jQuery)
http://docs.jquery.com/Using_jQuery_with_Other_Libraries#Referencing_Magic_-_Shortcuts_for_jQuery

Related

lodash bind function using as jQuery eventHandler... is it possible?

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.

Is there any benefit to defining a utility function directly on the jQuery object?

Are there any specific benefits derived from defining a utility function directly on the jQuery object:
For instance, given the following two constructs:
$.someUtility = function(){
//do some something with jQuery
}
var someUtility = function(){
//do some something with jQuery
}
Is there any specific reason I would want to use the first example over the second?
Quick Update:
I don't need to do any chaining, and my utility is not a plugin in the traditional sense; It will not perform any operations on a jQuery selector.
You're simply borrowing the global jQuery function object to make your function available to other scripts without further polluting the global variable environment.
If you have no other scripts that rely on that function, you could make it a local variable with no disadvantage except that you'd be polluting your local variable environment.
If you're strictly writing a utility function as opposed to a wrapper method I think the main benefit would simply be that your coding style would be more consistent. A consistent style could be important to you if you plan on using the function on more than a single page.
Three good reasons can be found for choosing to append functions directly on the JQuery object:
you want to build a JQuery plugin (most obvious reason)
the function you are programming applies to DOM nodes, so it could be directly applied to the DOM nodes returned by a JQuery query (sorry for the rhyme)
to keep consistency throughout your code, as you will be lead to use the $ object
Use $.fn.someUtility.
Basically, the first option is creating a jQuery plugin. This allows for your code to be easily reusable in the jQuery context. Inside a jQuery plugin, the this identifier points to the element that was selected in the jQuery selector, allowing for more flexibility when manipulating elements.
I guess the answer to your question is that it really depends. Are you using your function in multiple places?
See JQuery Plugins for more information.
The reason is that your function can then operate on arrays of jQuery-wrapped objects without jumping through the usual hoops. Also in the context of your function, this becomes a reference to the jQuery object on which your function was invoked.
EDIT
My answer assumed defining your function under $.fn.func.
Unless you require access to jQuery selected elements, the only benefit I can see would be by defining under $.func is that you avoid name collisions with other functions defined in the global scope. (As mentioned in my comment below.)
If your utility function uses jQuery (and thus requires it's presence), then I'd say you can use their namespace and put it under $.fn.myUtility as others have recommended. If your utility function is entirely independent of jQuery and does not use it at all and you are likely to have other such utility functions to go with it, then I would tend to make my own global namespace and put your function there such as JLF.myUtility. This makes your code a little easier to reuse in the future even in non-jQuery project.
For me, jQuery gets a lot of it's flexibility and power from the "daisy chain" setup, since every plugin returns "this" you can always call another plugin immediately after, not to mention you are extending an already powerful tool, and that seems like a good idea:)

Should I check for a element on a page before calling the Jquery plugin or call it and allow it to fail if not there

I have recently been wondering what would be the most friendly/efficient way to use plugins that have been bundled together to leverage caching. Are plugins are tied to HTML modules that are used sporadically in the site and have been called by using this kind of pattern:
if($('.moduleClass').length) {
$('.moduleClass').modulePlugin();
}
So we check for the module before we call the plugin. I have been wondering if this is the best solution or should I just be allowing jQuery to handle the fail if the browser doesn't find the element.
$('.moduleClass').modulePlugin();
Any idea, thoughts and experiences would be greatly received.
Thanks,
Ad
Doing 2 DOM lookups, is slower than doing 1.
Let jQuery handle it, there shouldn't be an error if there are no elements with the class 'moduleClass', nothing should happen.
I'd recommend not checking for existing explicitly. Just try to find a DOM element and call methods on it. Even if the element does not exist. jQuery handles this for you.
About speed: You're doing two DOM lookups in your first example, which is obviously slower than your second example. And even if you cached the jQuery object in the first example, it's still one lookup in each example.
Well, from the start, you're already calling .length on what could have been an empty set. jQuery lets you do that because it handles stuff like non-existent elements correctly.
Now, whether or not your plugin does the same is a whole different question. Nonetheless, I recommend against checking first anyway. If the plugin does not handle empty sets properly (especially since jQuery -- which it's built on -- does), I'd think again about using it.
I learned that if the plugin sucks it makes sense to check for it.
But if the plugin itself does a check via length or each(). There is nothing to gain by checking with length.

Why build Javascript functions as jQuery plugins?

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.

Is it possible to mix MooTools with Prototype and JQuery UI?

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.

Categories

Resources