JavaScript Programmer’s Reference by Jonathan Reid & Thomas Valentine

JavaScript Programmer’s Reference by Jonathan Reid & Thomas Valentine

Author:Jonathan Reid & Thomas Valentine
Language: eng
Format: epub
ISBN: 9781430246299
Publisher: Apress


Data Caching

As you do more asynchronous programming with XMLHttpRequest, it’s not uncommon to find yourself wanting to cache data locally for speed and efficiency. This is particularly true with mobile applications, where having a local cache of data can not only speed up your application (because accessing cached data is faster than going over the potentially quite slow network) but also make your application use less battery power (because accessing the network requires power). Even for desktop applications it’s common to want to cache commonly used information that doesn’t change very often.

Data caches are very simple, and typically consist of an identifier representing the service or data source, a timestamp of the last time the service was accessed, and the data that was returned the last time the service was accessed. Every time you look at the cache, you can see if the data you want is cached; if it isn’t, you can simply call the service and cache it with a new timestamp. If there is data in the cache, you check its timestamp. If it was accessed too long ago, you’ll know you need to access the service and cache the new results. But if it wasn’t accessed too long ago, you can just use the cached data.

We’ve already built a doXHR() function in the Asynchronous Communication using XMLHttpRequest section above. When we call that method, we provide an object that specifies the URL to call, as well as other information (such as a success method to call, or an error method to call). What would be nice is if we specified a length of time as a property, the doXHR() function would know that we want to cache the data from that URL and it could perform as follows:

Check to see if there is already data in our hypothetical cache.

If the data does not exist in the cache, go and fetch the data from the URL, and save it in the cache with the current timestamp.

If the data does exist in the cache, check the timestamp.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.