0

When I'm debugging a Javascript function in a browser and modify the code on the server, I want to reload the function in browser without having to refresh the whole page.

I've tried useing Firebug's Net panel to resend the GET request for the specific JS file. The content of the JS file is reloaded, but when I'm debugging in Script panel, it still executes the old code.

It is really important for my project, because it has a single page work flow. If I want to test the logic at step 2, I have to refresh the page and perform step 1 again every time.

BTW, I use RequireJS to load dependencies.

user1438980
  • 187
  • 1
  • 3
  • 13
  • hard to understand you question without code block. please edit your question by adding the code. Not all of it but just the parts where the problem exist. – TheProvost Oct 31 '14 at 02:08
  • you mean like http://stackoverflow.com/questions/19514993/reload-updated-javascript-code-without-fully-reloading-the-html-page ? or like http://stackoverflow.com/questions/9642205/how-to-force-a-script-reload-and-re-execute ? – Roko C. Buljan Oct 31 '14 at 03:07
  • This is a broad topic. Personally, I think roll-your-own solutions are going to be hacky and dysfunctional. First, check your editor/IDE's documentation to see if they have this kind of feature, for example, WebStorm appears to. Second, consider using the "workspace" feature in Chrome devtools which can automatically reflect changes made during debugging back to the source files, although I have not tried this myself. Similar solutions exist for CSS, like something called LiveStyle, although I have no personal experience with this. –  Oct 31 '14 at 03:19

1 Answers1

1

Haven't tested this too thoroughly, but I think you can do this by creating a new script tag (with an altered query string to force the browser to see it as a new script).

function reload_script_id(id) {
    return reload_script(document.getElementById(id));
}

function reload_script(old_script) {
    var new_script = document.createElement('script');
    new_script.src = change_query_string(old_script.src);
    replace_preserving_id(old_script, new_script);
    return new_script;
}

function replace_preserving_id(old_el, new_el) {
    var id = old_el.id;
    old_el.parentNode.appendChild(new_el);
    old_el.remove();
    new_el.id = id;
}

function change_query_string(url) {
    return [url.split('?')[0], Math.random()].join('?');
}

For example if you have

<script id="abc" src="some-script.js"></script>

then you can call

reload_script_id('abc');

and it will be replaced with something like

<script id="abc" src="some-script.js?0.7407381518278271"></script>

(Here's a jsfiddle demonstrating this.)

Chris Martin
  • 30,334
  • 10
  • 78
  • 137