Chrome doesnโ€™t show the updated content of an external JS file that is dynamically loaded on an HTML page

I have simple HTML and JS code. When the user selects the Italian language option, then the JS code dynamically loads the 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> 

language_it.js has the following line of code:

 alert ("Italian"); 

It works fine in Firefox, but if I change the contents of language_it.js , then Chrome will not display the updated content unless I restart the index.html page in Chrome . Is there a solution to this problem?

+4
source share
3 answers

If your cache stops updating your script correctly, or you want it to always be locked during production, you can always do something like this:

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

This will add a time-based lowercase digit that will almost always give you a unique number at the end of your URI, which should stop the browser from extracting the file from the cache.

+5
source

When developing in Chrome, you can disable the cache

  • Press F12 to open the developer tools.
  • In the lower right corner, click the gear icon.
  • Check "Disable Cache".
  • Reload the page.
+7
source

If you just need a .js file to update during development, disable the cache, as Joseph suggested.

If you want the JavaScript file to be updated every time it is called (if, for example, you dynamically generate it, for example), you can add a unique query string to the file name, which will cause the browser to extract it every time:

 scrptE.setAttribute("src", "language_it.js?ticks=" + new Date().getTime());โ€‹ 
+2
source

Source: https://habr.com/ru/post/1414122/


All Articles