I'm working on a google maps loader (using the google maps javascript API). I want to dynamically add points to a path as and when they come available. Edit: The webpage and javascript are stored and loaded locally and not through a web server.
To this end I have created an external javascript file in which I put the data I want to use.
I load the java script object using a great trick I found elsewhere on stackoverflow:
function loadjsfile( filename, callback )
{
var fileref = document.createElement( 'script' );
fileref.setAttribute( "type", "text/javascript" );
fileref.setAttribute( "src", filename );
var done = false;
fileref.onload = fileref.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
// Handle memory leak in IE
fileref.onload = fileref.onreadystatechange = null;
document.getElementsByTagName( "script" )[0].removeChild( fileref );
}
};
document.getElementsByTagName( "script" )[0].appendChild( fileref );
}
This works perfectly as it waits until the external javascript has actually loaded before proceeding with the intialisation.
So thats all great it loads up fine. I then set a 5 second timeout which reloads the external javascript file. This is where I have an issue. Google chrome is re-loading the external javascript file from cache instead of going straight to disk. This is a huge pain as it means that my map path doesn't update as it goes along. I really need it to.
When I refreshed the entire page then it was fine it reloaded the javascript but the flicker was very annoying (and it forced the map back to the "initial" state). This new method would work perfectly provided I could force it to re-load the javascript file everytime.
So can anyone help me?
I'm very new to Javascript (I'm mainly a C++ coder) so apologies if I'm asking something stupid :D
If noone else has other ideas, try appending a random number as a query string to the filename. This will tell the script the file is new and should force a reload.
Basically generate a random number each time.
var rnd = Math.floor(Math.random()*80000);
So you code would look something like
function loadjsfile( filename, callback )
{
var rnd = Math.floor(Math.random()*80000);
var fileref = document.createElement( 'script' );
fileref.setAttribute( "type", "text/javascript" );
fileref.setAttribute( "src", filename + "?r=" + rnd ); // note this line
// other code...
}