User:SD0001/userscript-load-caching.js

// Enable caching for resource loads, see User:SD0001/Making_user_scripts_load_faster, @revision 7 if (!/\bnocache=\b/.test(location.href)) { // Don't enable if nocache=1 url parameter is given let config = mw.config.values; let ctypeJs = 'text/javascript'; let ctypeCss = 'text/css'; let loadResource = (page, sitename, ctype) => { page = page.replace(/special:mypage/i, 'User:' + config.wgUserName); return $.get(			'https://' + sitename + '/w/api.php?titles=' + page + // page is already URL-encoded			'&origin=*&format=json&formatversion=2&uselang=content&maxage=86400&smaxage=86400' + 			'&action=query&prop=revisions|info&rvprop=content&rvlimit=1&inprop=protection'		).then((apiResponse) => {			let apiPage = apiResponse.query.pages[0];			if (!apiPage.missing) {				if (apiPage.ns !== 2 && apiPage.ns !== 8 && !apiPage.protection.find(p => p.type === 'edit' && p.level === 'sysop')) {					return $.Deferred.reject('Refused to load "' + page + '"@' + sitename + ': unprotected page');				}				let content = apiPage.revisions[0].content;				if ((!ctype || ctype === ctypeJs) && apiPage.contentmodel === 'javascript') {					let scriptTag = document.head.appendChild(document.createElement('script'));					scriptTag.innerHTML = content;			   } else if (ctype === ctypeCss && apiPage.contentmodel === 'css') { mw.loader.addStyleTag(content); } else { return $.Deferred.reject('Refused to load "' + page + '"@' + sitename + ': content type mismatch'); }			}		});	};	let serverName = config.wgServerName;	let getSiteTitle = (url) => {		let siteRgx = /^(?:(?:https:)?\/\/(.*))?\/w\/index.php/.exec(url),			titleRgx = /\btitle=([^=?&]*)/.exec(url);		if (siteRgx && titleRgx && /\baction=raw\b/.test(url) && /\bctype=/.test(url)) {			return [titleRgx[1], siteRgx[1] || serverName];			} else return null;	};	window.importScript = (page) => {		loadResource(encodeURIComponent(page), serverName, ctypeJs);	};	window.importStyleSheet = (page) => {		loadResource(encodeURIComponent(page), serverName, ctypeCss);	};	let oldMwLoaderLoad = mw.loader.load;	mw.loader.load = function(url, type) {		let linkParts = getSiteTitle(url);		if (linkParts) {			loadResource(linkParts[0], linkParts[1], type);		} else {			oldMwLoaderLoad.apply(mw.loader, [...arguments]);		}	};	let oldMwLoaderGetScript = mw.loader.getScript;	mw.loader.getScript = function(url) {		let linkParts = getSiteTitle(url); if (linkParts) { return loadResource(linkParts[0], linkParts[1], ctypeJs); } else { return oldMwLoaderGetScript.apply(mw.loader, [...arguments]); }	}; }