Even elementary DOM lookups in JavaScript, by element ID or class name, take considerable time by the browser, especially if the document is large.
Consider the following:
<div id="my-window"> ... </div>
A 'normal' jQuery way to locate the above DIV element by its ID would be as follows:
var $my_window = $('#my-window'); // expensive document traversal!
(Note that $('...')
always represents a collection in jQuery, even if there is only a single element that matches the selector.)
If over the lifetime of your page you need to refer to that DIV multiple times in your script, such repeated lookups consume extra CPU cycles, causing your page to appear slow and ultimately degrading end user experience. What the author is suggesting is to perform such expensive lookups only once and store the results in a local cache of sorts, which is just a JavaScript object holding a bunch of references. Those references can then be reused as needed very quickly:
var jqueryMap = {}, setJqueryMap;
setJqueryMap = function () {
jqueryMap = {
$my_window: $('#my-window'),
// store other references here
};
};
All you need to do is to call setJqueryMap
function once when your module loads. Then you can refer to the desired element (or elements) by their 'cached' references:
setJqueryMap();
...
jqueryMap.$my_window // do something with the element
That way the repeated traversals are avoided, making your script to perform much faster.