Is there a way to “hot swap” JavaScript code within the browser?

后端 未结 6 1407
南方客
南方客 2020-12-28 09:16

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,

6条回答
  •  梦毁少年i
    2020-12-28 09:29

    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

    add that to the location of a new bookmark, and it will reload all the javascripts referenced in . 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);
        }
    }
    

提交回复
热议问题