User:Dixtosa/CacheableStorage.js
Note: You may have to bypass your browser’s cache to see the changes. In addition, after saving a sitewide CSS file such as MediaWiki:Common.css, it will take 5-10 minutes before the changes take effect, even if you clear your cache.
- Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
- Konqueror and Chrome: click Reload or press F5;
- Opera: clear the cache in Tools → Preferences;
- Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.
- This script lacks a documentation subpage. Please create it.
- Useful links: root page • root page’s subpages • links • redirects • your own
var StorageWrapper = function(){
this.localStorageAvailable = mw.storage.get("localStorageTest") !== false;
this.storageAvailable = this.localStorageAvailable || navigator.cookieEnabled;
this.cookiePreferences = {
expires: 30, path: '/'
};
this.set = function(name, value){
if (this.localStorageAvailable) {
localStorage[name] = value;
} else {
$.cookie(name, value, {});
}
};
this.get = function(name) {
if (this.localStorageAvailable){
return localStorage[name];
} else {
return $.cookie(name);
}
};
};
window.CacheableStorage = function(productName, getProductCallback, expireInDays, version){
this.storageWrapper = new StorageWrapper();
this.StorageAvailable = this.storageWrapper.storageAvailable;
this.expireInDays = expireInDays;
this.version = version || 1;
this.productName = productName;
this.getProductCallback = getProductCallback;
this._cachedData = null;
this.itemAddressPrefix = "enwikt/CacheableStorage/" + this.productName + "?v=" + this.version;
this.itemDataAddress = this.itemAddressPrefix + "&Type=Data";
this.itemTypeAddress = this.itemAddressPrefix + "&Type=Type";
this.itemExpirationAddress = this.itemAddressPrefix + "&Type=Expiration";
this.refreshData = function() {
var this1 = this;
this.getProductCallback().then(function(d) {
this1.storageWrapper.set(this1.itemTypeAddress, typeof(d));
this1.storageWrapper.set(this1.itemExpirationAddress, new Date().toISOString());
if (typeof(d) != "string") d = JSON.stringify(d);
this1.storageWrapper.set(this1.itemDataAddress, d);
});
};
this.GetItem = function(){
if (this._cachedData)
return this._cachedData;
var data = this.storageWrapper.get(this.itemDataAddress);
var type = this.storageWrapper.get(this.itemTypeAddress);
var expiration = this.storageWrapper.get(this.itemExpirationAddress);
if (data)
{
if (type != "string") data = JSON.parse(data);
if ((new Date() - new Date(expiration))/1000 > this.expireInDays*24*3600){
this.refreshData();
return data;
}
else
return this._cachedData=data;
}
else
{
this.refreshData();
}
return null;
};
};