User:SD0001/Making user scripts load faster
Appearance
User scripts can be made to load faster with the help of caching.
Add the following code to the top of your your common JavaScript page:
// Enable caching for resource loads, see [[User:SD0001/Making_user_scripts_load_faster]]
function loadResource(page, sitename, contentType) {
return $.get(
'https://' + sitename + '/w/api.php?titles=' + encodeURIComponent(page) +
'&origin=*&format=json&formatversion=2&uselang=content&maxage=86400&smaxage=86400' +
'&action=query&prop=revisions&rvprop=content&rvlimit=1'
).then(function(apiResponse) {
var content = apiResponse.query.pages[0].revisions[0].content;
if (!contentType || contentType === 'text/javascript') {
eval(content); // jshint ignore:line
} else if (contentType === 'text/css') {
mw.loader.addStyleTag(content);
}
});
}
window.importScript = function(page) {
loadResource(page, mw.config.get('wgServerName'), 'text/javascript');
};
window.importStyleSheet = function(page) {
loadResource(page, mw.config.get('wgServerName'), 'text/css');
};
function shimMwLoader(oldFunction, disableReturn) {
return function(link, contentType) {
var resource = mw.loader.using('mediawiki.Uri').then(function() {
try {
var uri = new mw.Uri(link);
if (uri.protocol === 'https' && uri.host && uri.query.title && uri.query.action === 'raw') {
return loadResource(uri.query.title, uri.host, contentType);
} else {
return oldFunction.apply(mw.loader, Array.prototype.slice.call(arguments));
}
} catch(e) {
return oldFunction.apply(mw.loader, Array.prototype.slice.call(arguments));
}
});
if (!disableReturn) return resource;
};
}
mw.loader.load = shimMwLoader(mw.loader.load, true);
mw.loader.getScript = shimMwLoader(mw.loader.getScript);
Note that this code block necessarily needs to go at the top of the page for it to take effect.
Caveats
The snippet above makes all scripts and stylesheets cached by your browser for up to one day (86400 seconds).
If any of the scripts are updated, it may take you up to 1 day to see the updates. However, doing a hard reload will clear the caches. On Google Chrome, just hitting the "reload" button on any page causes a hard reload. On other browsers, you may need to use Ctrl+F5.