user1438980
user1438980

Reputation: 187

How can I reload a Javascript file on a webpage?

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.

Upvotes: 0

Views: 365

Answers (1)

Chris Martin
Chris Martin

Reputation: 30736

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.)

Upvotes: 1

Related Questions