Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery optimization - anything wrong with storing a jquery object reference?

I have a web-based application which is very highly reliant on jquery / javascript, and its sometimes a bit slow. One of the things that gets done frequently is changes to the grid (jqGrid) which means each time I'm using jQuery to select that object, ie:

function load_editor() { $('#listview').jqGrid(do_stuff); }

I believe simply storing a reference to $('#listview') - since its used in a half dozen functions - would be quicker. So is there any drawback to setting it up like this:

listview = $('#listview');
function load_editor() { listview.jqGrid(do_stuff); }

It would seem this way common objects are already in memory, and wont incur the penalty of the lookup on each use. Is there any downside to structuring this way?

( I'm aware in my examples, I'm throwing out a global. Its all nicely encapsulated in an object in the actual project, I just am using these examples to illustrate my point. )

like image 296
Stomped Avatar asked Apr 13 '26 07:04

Stomped


1 Answers

Absolutely you should.

And I strongly recommend you follow the style of the linked article - name your jQuery object variables with a $ prefix. Knowing which of your variables are jQuery objects just by looking at them will be of great help to you when your project becomes large.

like image 134
Peter Bailey Avatar answered Apr 14 '26 19:04

Peter Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!