Is there a way to "hot swap" JavaScript code within the browser?
debugging, frameworks, javascript
Solution
Interesting idea :)
I wrote the following bookmarklet:
function reload(){var scripts=document.getElementsByTagName("script");var head=document.getElementsByTagName("head")[0];var newScripts=[];var removeScripts=[];for(var i=0;i<scripts.length;i++){var parent=scripts[i].parentNode;if(parent==head&&scripts[i].src){var newScript={};newScript.src=scripts[i].src;newScript.innerHTML=scripts[i].innerHTML;newScripts.push(newScript);removeScripts.push(scripts[i]);}}for(var i=0;i<removeScripts.length;i++){head.removeChild(removeScripts[i]);}for(var i=0;i<newScripts.length;i++){var script=document.createElement("script");script.src=newScripts[i].src;script.type="text/javascript";script.innerHTML=newScripts[i].innerHTML;head.appendChild(script);}}
add that to the location of a new bookmark, and it will reload all the javascripts referenced in <head>. Not sure how well this will work in practice, but it was worth a shot :) I guess you'd have to be very careful in the way you write your scripts, so as not to have things added to the page body multiple times, etc. Maybe support for a 'reload="true"' attribute could be useful, that way you could tag only your libraries as reloadable.
Full source:
function reload() {
var scripts = document.getElementsByTagName("script");
var head = document.getElementsByTagName("head")[0];
var newScripts = [];
var removeScripts = [];
for(var i=0; i < scripts.length; i++) {
var parent = scripts[i].parentNode;
if(parent == head && scripts[i].src) {
var newScript = {};
newScript.src = scripts[i].src;
newScript.innerHTML = scripts[i].innerHTML;
newScripts.push(newScript);
removeScripts.push(scripts[i]);
}
}
for(var i=0; i < removeScripts.length; i++) {
head.removeChild(removeScripts[i]);
}
for(var i=0; i < newScripts.length; i++) {
var script = document.createElement("script");
script.src = newScripts[i].src;
script.type = "text/javascript";
script.innerHTML = newScripts[i].innerHTML;
head.appendChild(script);
}
}
Problem
Is there any tool that enables you to "hot swap" JavaScript contents while executing a webpage? I am looking for something similar to what HotSpot does for Java, a way to "hot deploy" new JS code without having to reload the whole page. Is there anything like that out there? Clarifying in case people don't understand "hot swap", as indicated by lock: By "hot swap" I mean allowing me to change parts of the code contained on the page itself and its .js files. Then this framework would detect the change - either automagically or by some indication from my end - and reload the code dynamically, avoiding the new server-side post (reload). That kind of approach would simplify debugging and error fixing, since you don't need to reload the page and start the interaction all over again, from scratch.