2

Hello guys i have a big doubt.... In my javscript code i need to reload a js file (where there's a multidimensional array) every 1 minutes. To reload it suggest me to use ajax or another way ?

Example A:

       try { 
          jQuery.ajax({             
            url: "http://www.fake.con/scripts/out/array/week-quakes.js",
            dataType: "script",
            cache: false
          });
        }
        catch(e){
            var aggiungi= '<span>there's error about server</span>';
            $(aggiungi).appendTo('#lista-eq');    
        }

Example B

$("head script[src='http://www.fake.con/scripts/out/array/week-quakes.js']").remove();


$('head').append('<script type="text/javascript" src="http://www.fake.con/scripts/out/array/week-quakes.js"><\/script>');   

These codes are inside setInterval(function())

However my problem is also that when i realod js file is possible it isn't ready or doesn't exist, so how can i solve this problem ?

I hope can you help me and suggest good :)

Borja
  • 3,359
  • 7
  • 33
  • 66

1 Answers1

3

I would go for something like that. First remove the old version. Then create a new element with the new one and add some sort of "cachebuster" to the url, so it doesn't reload the cached version.

let loadJsScript = function(src) {
    let oldScript = $("script[src='" + src + "']"),
        script = document.createElement('script');

    oldScript && oldScript.remove();

    script.type = 'text/javascript';
    script.src = src

    $('head').append(script);
}


loadJsScript('/scripts/out/array/week-quakes.js?cachebuster='+ new Date().getTime());

To run the function every minute you would wrap it with setInterval function.

setInterval(function(){ 
 loadJsScript('/scripts/out/array/week-quakes.js?cachebuster='+ new Date().getTime());
},60000)
Aleksei Maide
  • 1,845
  • 1
  • 21
  • 23
  • infact i noticed that sometimes reload the cached version... however your code is a bit difficult for me (i'm not good programmer :P) can you say me if can i put "loadJsScript" variable outside event ready() like global variable ? thanks a lot – Borja Mar 07 '18 at 11:37
  • 1
    @Borja nothing prevents you from making it global. you could even make it a window object property, such as window.loadJsScript etc... as a result you will be able to call in anywhere. BUT If you intend to use it before the page is loaded, you could just link the script in html, couldn't you? – Aleksei Maide Mar 07 '18 at 11:41
  • one last thing... can i use also "var" or only "let" in this case ? – Borja Mar 07 '18 at 11:53
  • 1
    @Borja You can use either, but check this for more information: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable – Aleksei Maide Mar 07 '18 at 11:54