I am working on an intranet website where there is a lot of interaction with the main page. The site uses jQuery extensively. So I thought about caching the jQuery selections the first time they are requested and pull them from the cache for each subsequent request. (I also have built in an override if I want to force a re-selection).
Here is the basic snippet of code I am wondering about:
( function(window, $, undefined) {
var mp = {};
mp.cache = [];
mp.get = function ( selector, force) {
return ( !force || !mp.cache[ selector ] ) /*separating for readability */
? mp.cache[ selector ] = $( selector )
: mp.cache[ selector ];
}
/* more functions and code */
window.mp = mp;
window.$$ = mp.get;
})(window, jQuery);
It would be used just like a normal jQuery selection but checks to see if that selector already exists in the cache
array and, if it does, just returns the results from there.
UPDATED EXAMPLE
$('#mainmenu').on('click','.menuitem', highlightSelectedMenuItem );
function highlightSelectedMenuItem () {
var menuitems = $$('.menuitem'); //selected first time, from cache every other time
menuitems.find('.current').removeClass('current');
$(this).addClass('current');
}
There are about 20 - 30 different selections in the code. So each would be cached on first call. This code will only be run on desktop clients (no phones/tablets).
Good idea? Any issues this might cause? Is there a good way to test if this helps/hurts performance? Any pros/cons you can come up with would be appreciated.
Let me know if more information is required.
Here is a fiddle to "fiddle" with.
Thanks!