User:Manishearth/purger.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* My script purger for developers
This script will bypass your browser's cache for '''only''' the scripts listed in a cookie. This speeds up development.
For this script to work, all the imports you want this to apply to should go to [[Special:MyPage/imports.js]]
ADD ALL IMPORTS THERE, even ones you don't want purged. This script will purge the scripts in the cookie and no more.
The imports.js subpage is only so that the imports are executed after this script is executed.

*/


//Init stuff, nothing important
if(!readCookie("devMode")){
createCookie("devMode","",365)
}
addOnloadHook(function(){

mw.util.addPortletLink("p-tb","javascript:createCookie('devMode',prompt('Change the autopurge pages: (Separate the script names with commas, please). \n Do NOT press cancel, or all the data in the cookie will be erased. Instead, press Ok.',readCookie('devMode')),365)","Purge scripts") // Sets the cookie with a prompt if clicked, the default text of the prompt is the current value of the cookie


});

//OVERRIDE importScript
function importScript(page) {
	// copy of importScript, except it allows purging
	var devTail="&rand="+parseInt(Math.random()*100000); //A random tail
	devTail2=(readCookie("devMode").toLowerCase().indexOf(page.toLowerCase())!=-1)?devTail :''; //Decide if the cookie tells us to purge
	var uri = mw.config.get('wgScript') + '?title=' +encodeURIComponent(page.replace(/ /g,'_')).replace(/%2F/ig,'/').replace(/%3A/ig,':') + '&action=raw&ctype=text/javascript'+devTail2; //Add the tail
	return mw.loader.load(uri);
}

var undefined;
function importScriptPurged(page,seed) {
	if(seed===undefined){seed=parseInt(Math.random()*10000)}
	var devTail="&rand="+seed;
	var uri = mw.config.get('wgScript') + '?title=' +encodeURIComponent(page.replace(/ /g,'_')).replace(/%2F/ig,'/').replace(/%3A/ig,':') + '&action=raw&ctype=text/javascript'+devTail;
	return mw.loader.load(uri);
}

//Force purge imports.js, any changes made there will go live immediately
importScriptPurged("User:"+mw.config.get('wgUserName')+"/imports.js")


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}