Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching problem with asynchronous javascript loading with onload event

I am currently trying to load some js files asynchronously, so that they are not able to block the rest of the website. I mainly followed the descriptions found here:

Asynchronous Javascript

In terms of the non blocking loading of the javascript file this works great, but i got now the problem that the javascript file is cached and stays cached even if i change the content (also doing shift-reload does not help anything).

My current code of loading the script looks like the following:

 (function() {
   function xx_async_load() {
     var xx = document.createElement('script');
     xx.type = 'text/javascript';
     xx.async = true;
     xx.src = 'http://myserver.de/myjs.js';
     var el = document.getElementsByTagName('script')[0];
     el.parentNode.insertBefore(xx, el);
   }

   if (window.addEventListener) {
     window.addEventListener('load', xx_async_load, false);
   } else if (window.attachEvent){
     window.attachEvent('onload', xx_async_load);
   }

 })();

If i call the code inside "xx_async_load" directly and change the myjs.js, the changes are getting recognized, but if I am loading this through the onload event it always stays cached and the changed are never recognized.

Does anybody know a solution how I make the browser to recognize the changes in the cached files (problem appears in Opera, FF and IE work fine)?

EDIT: If i look at the "Network" tab of Operas Dragonfly, there isn't even a request done on reload for the cached JS file, it seems that it is directly loading it from cache without even checking against the file on the server.

EDIT2: I will test how long it stays in the cache. If its gone till tomorrow its fine. Else I can still propose the workaround with a date param (so accepting that answer). Thx again.

like image 716
enricog Avatar asked Oct 15 '25 15:10

enricog


1 Answers

Yes, this is fairly simple.

Just give a random parameter to your URL, like : URL = http://www.yoururl.com -> http://www.yoururl.com/?number=(random number)

this way you will always have a unique url. the parameter will be thrown away by the page when it is loaded because it is not used.

Let me know if this helped

like image 100
Nealv Avatar answered Oct 18 '25 06:10

Nealv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!