Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save OlivierPerceboisGarve/478482 to your computer and use it in GitHub Desktop.
Save OlivierPerceboisGarve/478482 to your computer and use it in GitHub Desktop.
/*!
* $imple cache - v0.3pre - 07/15/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,window){
'$:nomunge'; // Used by YUI compressor.
// Do both window.$ and window.jQuery need to be set?
var set_both = $ === window.$,
// Element expando + unique ID for caching.
expando = '$implecache' + +new Date(),
guid = 0,
cache = {};
window.jQuery = function( selector, context, use_cache ) {
var result,
key,
id;
// `context` arg wasn't passed, but `use_cache` was.
if ( typeof context === 'boolean' ) {
use_cache = context;
context = undefined;
}
// Use cache.
if ( typeof use_cache === 'boolean' ) {
// Generate a unique id from the passed selector and/or context.
key = get_key( selector ) + '__' + get_key( context );
// If `use_cache` is true and the cache is populated, return that.
if ( use_cache && cache[ key ] ) {
return cache[ key ];
}
}
// Call the original jQuery function with selector and context.
result = $( selector, context );
// Since the cache is being used, update it for next time.
if ( key ) {
cache[ key ] = result;
}
return result;
};
// This logic probably needs to be improved a bit.
function get_key( val ) {
var result,
id;
if ( val === undefined ) {
result = '';
} else if ( typeof val === 'string' ) {
result = val;
} else if ( val instanceof jQuery ) {
result = val.selector;
} else {
id = val[ expando ] || ( val[ expando ] = ++guid );
result = expando + id;
}
return result;
};
// Update both jQueries, if applicable.
if ( set_both ) {
window.$ = window.jQuery;
}
})(jQuery,this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment