开发者

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

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 开发者_如何学Gois 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜