Reload JS file without page refresh

Martin Grey picture Martin Grey · Oct 23, 2015 · Viewed 7.7k times · Source

Is there any way, how I can force my browser to refresh (re-download) JS resources only, without refreshing the whole page? Solution in any web browser is fine. Of course, browser-independent solution would be the best.

Background: Our application has multiple screens on the same page. After some actions on one screen, AJAX fetches another screen. Since the page uses JS a lot, I often need to change its JS resources. After a refresh of the page to get the fixed JS, I have to go through all previous screens before I get to the one that I am currently debugging.

Answer

Martin Grey picture Martin Grey · Oct 26, 2015

You can use jQuery for this. In Firefox, you can write something like this directly to Firebug console:

$.getScript("http://example.com/path/to/your/file.js");

Note: the new script is downloaded on top of the old one. Any JS code that initializes the page is therefore executed again, which may have side effects. In pages with a lot of JS, it is often a good idea to put definitions of functions and constants into different file than page init code (like the binding of events to elements). Then you can use getScript() to get only the definitions file.

If you want to have all things in one file, you can clear old binds before you load the new file by:

$("*").off();