Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome does not show updated contents of external JS file which is loaded dynamically in HTML page

I have following simple HTML and JS code. When User selects Italian Language option then the JS code dynamically load an external JS file language_it.js.

<html>
<head>

<script>
function ChangePageLanguage()
{
var e = document.getElementById("langDD");
var lang = e.options[e.selectedIndex].value;

if (lang == "it")
{
    var scrptE = document.createElement("script");
    scrptE.setAttribute("type", "text/javascript");
    scrptE.setAttribute("language", "JavaScript");
    scrptE.setAttribute("src", "language_it.js");
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(scrptE);
}
}
</script>
</head>

<body>
<select onchange="ChangePageLanguage()" id="langDD">
    <option value="en">English</option>
    <option value="it">Italian</option>
    </select>
</body>
</html>

The language_it.js have following line of code:

alert ("Italian");

It works fine in Firefox but if I change contents of language_it.js then Chrome does not show the updated contents unless I restart the index.html page in Chrome. Is there any solution to this issue?

like image 542
Azeem Avatar asked May 24 '12 11:05

Azeem


3 Answers

When developing on Chrome, you can disable the cache

  • Press F12 to open the developer tools.
  • On the lower right corner, click the gear icon.
  • Check "Disable Cache".
  • Reload the page.
like image 180
Joseph Avatar answered Oct 16 '22 01:10

Joseph


If your cache is stopping your script from updating properly, or you need it to be always uncached in production, you can always do something like this:

scrptE.setAttribute("src", "language_it.js?" + (Date.now() % 10000));

That will append a time-based string of digits that will almost always give you a unique number at the end of your URI, which should stop the browser from retrieving the file from cache.

like image 27
Nimphious Avatar answered Oct 16 '22 01:10

Nimphious


If you just need the .js file to refresh during development, disable the cache like Joseph suggested.

If you need the JavaScript file to refresh every single time it's called (if you're dynamically generating it for example), you can add a unique querystring to the filename which will cause the browser to retrieve it every single time:

scrptE.setAttribute("src", "language_it.js?ticks=" + new Date().getTime());​
like image 40
Chris Van Opstal Avatar answered Oct 16 '22 00:10

Chris Van Opstal