Every web developer/web coder/web programmer should know the importance of JavaScript caching for web performance. With technology specifications of old HTML versions, we can only store JavaScript browser caches in cookie on client side, or do it on server side with session/other web storage solutions with files.
However in the new version of HTML - HTML5; besides the capabilities of offline cache (see more new features of HTML5 in HOT New JavaScript APIs with HTML5), HTML5 also give us the abilities of local storage to speed up the web performance.
This JavaScript article tutorial shows you some basic concepts and JavaScript code examples to build web applications with cache in HTML5. Please go to the full post page for details.
- Demo
- Enlarge
- Reload
- New window
Free iPage Web Hosting for First Year NOW
If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?
Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Every developer knows the importance of caching. From end to end you have caching on the backend (memcached, xcache, etc.) to prevent your databases being lit on fire, edge caching on content delivery networks (CDN's) in hopes that your browser will cache assets it sees more than once. And of course client-side caching so you don't repeat expensive operations (albeit algorithmically or high volume repitions). Here is a solution in JavaScript to help you out with the latter, with optional support for HTML5 Local Storage.
Starting Simple
function CacheProvider() {
// values will be stored here
this._cache = {};
}
Feature detect on local storage
try {
CacheProvider.hasLocalStorage = ('localStorage' in window) && window['localStorage'] !== null;
} catch (ex) {
CacheProvider.hasLocalStorage = false;
}
The main reason we use try / catch
is because despite Firefox supporting it, it can be disabled in your about:config
settings and an error will be thrown. A simple if / else
will not work.
Next we'll add support for storing objects into local storage. This
technique was borrowed from Christopher Blizzard in his excellent post Saving data with local storage - for which those who didn't know, you can only store string
's into local storage. Thus we have this...
in / out JSON parsing
if (CacheProvider.hasLocalStorage) {
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function(key) {
return JSON.parse(this.getItem(key));
};
}
Now for our three core methods, we'll have get, set, and clear.
Core class functionality
CacheProvider.prototype = {
/**
* {String} k - the key
* {Boolean} local - get this from local storage?
* {Boolean} o - is the value you put in local storage an object?
*/
get: function(k, local, o) {
if (local && CacheProvider.hasLocalStorage) {
var action = o ? 'getObject' : 'getItem';
return localStorage[action](k) || undefined;
} else {
return this._cache[k] || undefined;
}
},
/**
* {String} k - the key
* {Object} v - any kind of value you want to store
* however only objects and strings are allowed in local storage
* {Boolean} local - put this in local storage
*/
set: function(k, v, local) {
if (local && CacheProvider.hasLocalStorage) {
if (typeof v !== 'string') {
// make assumption if it's not a string, then we're storing an object
localStorage.setObject(k, v);
} else {
try {
localStorage.setItem(k, v);
} catch (ex) {
if (ex.name == 'QUOTA_EXCEEDED_ERR') {
// developer needs to figure out what to start invalidating
throw new Exception(v);
return;
}
}
}
} else {
// put in our local object
this._cache[k] = v;
}
// return our newly cached item
return v;
},
/**
* {String} k - the key
* {Boolean} local - put this in local storage
* {Boolean} o - is this an object you want to put in local storage?
*/
clear: function(k, local, o) {
if (local && CacheProvider.hasLocalStorage) {
localStorage.removeItem(k);
}
// delete in both caches - doesn't hurt.
delete this._cache[k];
}
};
How does this work?
Note in the beginning of this post, said Cache Provider was to have optional support for local storage (although it appears to be most of the point). First let's look at an example sans-local-storage.
getElementsByClassName
var cache = new CacheProvider;
window.getElementsByClassName = getElementsByClassName || function(c) {
var reg = cache.get(c) || cache.set(c, new RegExp("(?:^|\\s+)" + c + "(?:\\s+|$)"));
var elements = document.getElementsByTagName('*');
var results = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].className.match(reg)) {
results.push(elements[i]);
}
}
return results;
};
Note the next time you work with the same class - it work with a precompiled regular expression instead of constructing a new one.
As another example, for large apps that require i18n, you could cache the compiled HTML strings into local storage.
var i18nCache = new CacheProvider;
if (i18nCache.get('topnav')) {
$('#nav').html(i18nCache.get('topnav'));
} else {
ajax('top-nav.tmpl', function(html) {
i18nCache.set('topnav', html);
$('#nav').html(i18nCache.get('topnav'));
});
}
Other than that, have a play, do some caching, and outsource your resources to your users browser. cheers ;)
- Sent (0)
- New
Generate your business videos by AI with voice or just text
chatGPTaz.com
Talk to ChatGPT by your mother language
AppAIVideo
Your first FREE AI Video App
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing
Dall-E-OpenAI.com
Generate creative images automatically with AI
chatGPT4.win
Talk to ChatGPT by your mother language
First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language
Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools
GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project
iPhoneKer.com
Save up to 630$ when buy new iPhone 16
Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k