Borja
Borja

Reputation: 3559

Best and fast practice to reload an external javascript file?

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 :)

Upvotes: 2

Views: 297

Answers (1)

Aleksei Maide
Aleksei Maide

Reputation: 1855

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)

Upvotes: 3

Related Questions