View Full Version : Refresh an external javascript file from the server at intervals?

Subyne Simean
09-23-2012, 07:26 PM
Hi guys,

I have a webpage in which certain content will be called from a javascript file.

I will be linking to the file as follows:

<script type="text/javascript" src="js.js"></script>

The js.js file will be updated by an admin in my office.

Is it possible to have the js.js file called from the server periodically - say every 1800 seconds (to update the webpage without interrupting the user)?

Also can there be a link to manually call the js.js file as well, in case a user doesn't want to wait 1800 seconds for the next update?

I'm aware of the meta refresh tag but this would interrupt the user and erase text from the form fields that they need to use throughout the day.

Your help is greatly appreciated.

09-24-2012, 05:23 AM
the exact approach depends on the code, but you generally would want to use an "ajax refresh" of some type. searching the forums will bring up numerous examples. what does js.js do?

Old Pedant
09-24-2012, 05:54 AM
Yeah, Dan, but what he wants to do is *REPLACE* js.js

That can be done, and probably should be done using AJAX, but it's not a simple proposition.

09-24-2012, 08:54 AM
That can be done, and probably should be done using AJAX, but it's not a simple proposition.

It wouldn't be simple to do with AJAX and so shouldn't be done that way (unless you are using AJAX as a broad term to mean calling the server). It is really easy to do this with just a few DOM commands.

First you need a slight modification to the script tag.

<script type="text/javascript" src="js.js" id="js"></script>

You then use the following script to replace the script tag every 1800 seconds appending a different querystring to the src each time to prevent the currently cached copy being reused.

function() {var d, s;
d = document.getElementById('js');
s = document.createElement('script');
s.src = 'js.js?d='+ Date.now();
s.id = 'js';