Skip to content

Instantly share code, notes, and snippets.

@buzzedword
Created May 20, 2011 17:21
Show Gist options
  • Save buzzedword/983358 to your computer and use it in GitHub Desktop.
Save buzzedword/983358 to your computer and use it in GitHub Desktop.
Globalized storage for jQuery using a document fragment instead of $(element).data();
/*
* Notes: Optimized for "set" operations
* Performance test URL: http://jsperf.com/global-storage-vs-jquery
*/
(function($, unknown) {
// Usage: Instead of $(elem).data('key'), you use $.storage.get('key') for retrieval.
// Usage: Instead of $(elem).data('key', 'value'), you use $.storage.set('key', 'value') for set.
$.storage = {
get: function(key) {
if (typeof $.storage.db == 'undefined') {
$.storage.db = document.createDocumentFragment();
}
if (typeof $.storage.cache == 'undefined') {
$.storage.cache = {};
}
$($.storage.db).data($.storage.cache);
$.storage.cache = {};
if (typeof key == 'undefined') {
return $($.storage.db).data();
} else {
return $($.storage.db).data(key);
}
},
set: function(key, value) {
if (typeof $.storage.db == 'undefined') {
$.storage.db = document.createDocumentFragment();
}
if (typeof $.storage.cache == 'undefined') {
$.storage.cache = {};
}
if (typeof key == 'undefined' || typeof value == 'undefined') {
return undefined;
} else {
$.storage.cache[key] = value;
return value;
}
}
};
}(jQuery));
/*
* Notes: Optimized for "get" operations
* Performance test URL: http://jsperf.com/global-storage-vs-jquery-w-o-cache
*/
(function( $, unknown ) {
// Usage: Instead of $(elem).data('key'), you use $.storage.get('key') for retrieval.
// Usage: Instead of $(elem).data('key', 'value'), you use $.storage.set('key', 'value') for set.
$.storage = {
get: function(key) {
if (typeof $.storage.db == 'undefined') {
$.storage.db = document.createDocumentFragment();
}
if (typeof key == 'undefined'){
return $($.storage.db).data();
} else {
return $($.storage.db).data(key);
}
},
set: function(key, value) {
if (typeof $.storage.db == 'undefined') {
$.storage.db = document.createDocumentFragment();
}
if (typeof key == 'undefined' || typeof value == 'undefined') {
return undefined;
} else {
return $($.storage.db).data(key, value);
}
}
};
}
(jQuery));
@buzzedword
Copy link
Author

Updated to cached vs non cached.

Cached = key+val in set command, writes to .data() only on get.

  • Optimized for .set() operations

Non cached = writes to .data() directly in set commands.

  • Optimized for .get() operations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment