Some versions of Apache need a tweak
Some versions of Apache break AutoReload. They send the whole page every time (Status 200) instead of respondingthing with a status 304 unchanged. Unbelievably this bug refuses to be solved. It sure ruined my day. This means autoReload will continually refresh! Details The solution is to add FileETag none into apache2.conf. (I don't know the details and don't care if there are scary reasons for not doing this.)
You're coding a web page and want to see the effect of your changes. Fine, so leave your editor and reload the page by going to the browser and typing Ctrl-R. Now go back to the editor and so on. Wouldn't it be great if your page automatically refreshed as soon as you saved it? I can tell you after having the luxury of staying right in the editor you'll never go back to manually switching tasks.
All you need is need two <script>s and AutoReload.Start(); in 'document ready'.
Also you can
Watch for other multiple files changing
Save state across reloads
Write your own before and after reload functions
Change updating interval
It's so cool to Ctrl-S in the editor and see instant changes appear in browser without missing a beat.
Getting started is easy-peasy
The out-of-the-box option is for the page to reload itself, if changed, by checking once a second.
Shortcut
If you don't use jQuery and want a quick solution then put this in the head:
<script type="text/javascript" src="autoReloadAndJquery.js"></script>
Out of the box autoReload only watches the source of the page itself. That's not very exciting. If you add the property watched to <script> and <link> tags in the head then these will be watched as well.
AutoReload.Start(); returns the time at reload. This is one way to flag the page has actually reloaded. It is also a blunt reminder to remove autoReload before deployment.
$('#reloadTimeBanner').html(AutoReload.Start());See the top of this page for an example.
An alternative way to check autoReload is alive is to give the .Start() method an object containing the id of a DOM element in which to count time since last reload. I always use id=ARtimer and give .Start(){latencyId:"ARtimer"}. This has the advantage that you can see autoReload is still watching.
Sometimes, the polling of autoReload will timeout. This is typically due to an unusual load on browser or server. It stops because it thinks one or more files have gone missing. There are a couple of mitigations you can take:
Prune the number of links and scripts being watched by removing the watched flag.
Increase the polling interval. Give .Start() something like {interval:5000} for a 5 second poll frequency.
Sometimes you might have some build process which doesn't directly change any of the links or scripts. So long as there's some file, even a dummy flag file, or perhaps log file which changes you can get autoReload to watch it by giving .Start() an object like {WatchedList:["someFinishedBuildFile.txt"]}
Basic principle
Polling for changes
When your browser asks the server for a web page the server is supposed to know if you've already requested that page before and it hasn't changed since. If that is the case then the server sends a status code of 304 which means 'no changes' since previous request. AutoReload merrily runs through it's list of watched files asking for the status every second or so. Only if it finds say a 200 status will it refresh the page.
AutoReload is always asking 'has anything changed' rather than constantly refreshing.
List of watched files
AutoReload always watches its own source. If that's all you want to do then you're done. However if components need watching that's easy too as it it looks for the watched attribute in scripts and links. (In my experience you only need a few of these watched at a time.)
Sometimes something else in the background might warrant a reload. In this case manually add such a file to the watched list in the .Start() using the watchedList property.
Maintaining state across reloads
Sometimes while developing a page there will be content which is useful to save but a reload causes a 'reset everything'. Just before reloading, all elements with the AR-... classes are saved to localStorage, the page refresh done then those values restored.
Out of the box save state feature
There are configuration tweaks you can add to the .Start() method but there is ready-baked functionality for saving state between reloads. Suppose for sake of argument you have a select-box and you want the page to remember that selection across reloads (Some browsers might do it for you but the actual setting of the selection might trigger something else, and the page-load process might set everything back to 'blank') Many pages apply and remove classes to elements and that sort of thing doesn't get saved by a browser on a simple refresh.
Add one or more of the class AR-saveVal, AR-saveHtml,
AR-saveClasses or AR-saveChecked to elements and you're done. (Elements must have an id).
Demo Pick from the select box. When this changes the class of the sample text will be changed.
So far so good. A normal Ctrl-R ends up with the colour forced back to 'pick one' (and in my browser,
the select box showing another colour. Jings!)
In this demo the Clear history button purges all state (and reloads).
See how the select box reverts to 'neutral' to match the text colour.
Bonus The vertical scroll position is remembered so if you're working down the page you don't have to scroll back to where you were.
Multiple files and other goodies
By adding a configuration object to the .Start() call you can tweak the way AutoReload works. Say for example you want to change the interval from the default one second to two then you'd do this: AutoReload.Start({interval:2000});
Parameter
Type
Use
If absent
watchedList
Array of strings
Give the filenames to watch. For example ['index.htm','./style/my.css','./js/my.js']
These are relative to the current file or could be fully specified URLs
The current file can be referred to as [window.location.href, ...]
You can use full URLs http://etc.com/some/page.htm but this will quite likely fail if you try any cross-site shenanigans.
See below
The current file
interval
Number
The number of milliseconds between testing for changes. (This is the time between finishing checking and having another look, so if you have a slow server the actual time between tests will be extended.)
1000ms
latencyId
String
This is the id of a DOM element used to display how long since the last reload. This can be a handy check that the page actually has reloaded. (The counter changes quickly for low values then slows down so as to minimise distraction.) See below
Ignored
onLoadState onSaveState
Function
You can replace the default state save/load routines with custom code.
Out-of-the-box functionality
Editing the HTML during development
Hacking which files are currently watched
Having lots of files being continually watched can be painful. Instead of setting the watchedList parameter of the .Start() function just annotate the scripts and links to be watched with the watched keyword as in this example:
<script watched src="/bits/js/utility-min.js"></script>
<link watched href="jshint.css" rel="stylesheet" type="text/css">
Disabling eg. for production
Typically you've got a tiny bit of HTML to display the number of seconds since the last reload. This has the id to match latencyId. It might look like this: <span id="ARtimer" class="tiny">will be secs since reload</span>. To completely disable AR and remove the nominated DOM element, change the initial text in the element to disabled as for example: <span id="ARtimer"class="tiny">disabled</span>
API reference
Method
Description
Start(Optional object)
The only required call. See above for configuration parameters. Generally this wants to go at the bottom of the document-ready function.
Handy tipStart() returns the current time to help you check the page really has reloaded. You can console.log this or do something like $('#testBanner').html(AutoReload.Start();) which, by being visible on the page will remind you to remove it at release time.
SaveState()
Calls the save state routine immediately. Normally this will be done automatically just before a reload, and only then. If you anticipate doing manual refreshes (where state will not be saved) then add the following code to document ready. $(window).unload(function(){AutoReload.SaveState();});
PurgeState()
Clears all saved state and immediately reloads the page. Use this to return all state to the condition an ordinary user would see. See the demo code above.
Stop()
If for some reason you want to inhibit testing for changes.
LoadState()
This is done automatically on every page load so there shouldn't be any need to call it.
RememberRemove AutoReload before distribution.
Bits and bobs
Contact Peter Fox at @.
MIT licence. Make the best use you can of it.
I use it alll the time but it hasn't been tested within an inch of its life.
(All observations on the code, preferably with suggested improvements will be very welcome.)
Don't like jQuery? OK then, hack away.
The styles on this page comes from a completely self-contained css file. (Included in the download).
If you want to know more then go to Vulpeculox.net