Javascript 大规模jQuery选择器缓存
在大规模JavaScript应用程序中,有哪些模式可用于缓存许多jQuery选择器以重复使用 关于在简单函数中的简单变量中存储jQuery选择器,人们已经说了很多,但是在JavaScript对象中,例如在流行的模块模式中,如何干净地设置和存储它们呢 我最初的尝试是使用全局变量,但这会弄脏名称空间并可能导致冲突。我的第二次尝试涉及将选择器存储在相应对象内的对象文字中,但这会导致对它们的调用比预期的长,例如:Javascript 大规模jQuery选择器缓存,javascript,jquery,performance,Javascript,Jquery,Performance,在大规模JavaScript应用程序中,有哪些模式可用于缓存许多jQuery选择器以重复使用 关于在简单函数中的简单变量中存储jQuery选择器,人们已经说了很多,但是在JavaScript对象中,例如在流行的模块模式中,如何干净地设置和存储它们呢 我最初的尝试是使用全局变量,但这会弄脏名称空间并可能导致冲突。我的第二次尝试涉及将选择器存储在相应对象内的对象文字中,但这会导致对它们的调用比预期的长,例如: var Module = { nodes: {}, storeSelector
var Module = {
nodes: {},
storeSelectorsInCache: function() {
Module.nodes = {
form: $('#form'),
grid: $('#grid')
};
},
initialize: function() {
Module.storeSelectorsInCache();
// notice the long hierarchy to get to Module.nodes.form
Module.nodes.form.submit(function() {
// event handler
});
}
};
那里一定有更干净的速记法。像这样的东西可能很酷:
var _nodes = {};
var Module = {
/**
* You could call this when you want to query a selector and store it for reuse. Then
* just use this for querying.
*
* @param {String} selector The selector to memoize.
* @param forceUpdate {Boolean} jQuery selectors don't update with their DOM
* counterparts. This will take that into account. Pass in true to override cache.
*
* @return {Object<Array<jQuery>>} The matching selectors.
*/
$: function(selector, forceUpdate) {
if (forceUpdate === true || !({}).hasOwnProperty.call(_nodes, selector)) {
_nodes[selector] = jQuery(selector); // Not that robust, just a basic example
}
return _nodes[selector];
},
initialize: function() {
this.$('#form').submit(function () { /* ... */ });
}
};
像这样的东西可能很酷:
var _nodes = {};
var Module = {
/**
* You could call this when you want to query a selector and store it for reuse. Then
* just use this for querying.
*
* @param {String} selector The selector to memoize.
* @param forceUpdate {Boolean} jQuery selectors don't update with their DOM
* counterparts. This will take that into account. Pass in true to override cache.
*
* @return {Object<Array<jQuery>>} The matching selectors.
*/
$: function(selector, forceUpdate) {
if (forceUpdate === true || !({}).hasOwnProperty.call(_nodes, selector)) {
_nodes[selector] = jQuery(selector); // Not that robust, just a basic example
}
return _nodes[selector];
},
initialize: function() {
this.$('#form').submit(function () { /* ... */ });
}
};
您可以将
Module.nodes
分配给具有较短名称的变量,然后再使用该变量。或者您可以在IIFE中工作,然后只使用普通变量,从而避免污染全局命名空间,同时允许您为变量使用较短的较简单名称。简单(模块-)有什么错局部变量?真正的问题是为什么需要缓存选择器。您是否已确定它们是您的应用程序的瓶颈?我发现,当大多数选择以异步方式完成时(作为动画、ajax回调、事件等的一部分),选择的成本往往可以忽略不计。我有大约30个选择器,它们经常在密集型应用程序中重用。我使用缓存来衡量显著的性能改进。您可以将模块.节点
分配给具有短名称的变量,然后再使用该变量。或者您可以在IIFE中工作,然后只使用普通变量,这样可以避免污染全局名称空间,同时允许您为变量使用更短更简单的名称。简单(模块)局部变量有什么问题?真正的问题是为什么需要缓存选择器。您是否已确定它们是您的应用程序的瓶颈?我发现,当大多数选择以异步方式完成时(作为动画、ajax回调、事件等的一部分),选择的成本往往可以忽略不计。我有大约30个选择器,它们经常在密集型应用程序中重用。我衡量了缓存的显著性能改进。