Offline data cache (offline.js)

offline.js enables access to recently retrieved data when the application becomes disconnected. It can also act as a simple expiring data cache, or as a wrapper for localStorage access.

This library does not depend on anything else besides DOM Storage. If localStorage is not available, then it will simply not ever hold anything in cache. Nothing needs to change from the client perspective.

Primary Usage Pattern

To achieve both an expiring cache (for recently requested data) as well as an offline data cache, this is the pattern to integrate into your remote data access. To achieve just an offline data cache, skip step 1 or set expiry to zero.

  1. If offline.fresh(key), then return offline.get(key).
  2. Otherwise, execute remote API call.
  3. If remote API call was successful, store offline.set(key, value, expiry) and return value.
  4. If remote API call failed (e.g., status === 0), attempt offline.get(key).
  5. If value is missing, notify caller of offline/remote error.

lscache

This library began as a fork of the excellent lscache by Pamela Fox. While trying to implement the offline usage pattern, it became clear that some breaking changes needed to be made to the interface. Rather than confuse the two libraries, offline.js deviates from lscache.js to solve a related but slightly different problem:

Online / Offline Events

Initially, this was going to incorporate hooks for HTML 5 Online/Offline events. Ultimately, this seemed to only be partially useful and potentially broken. Even in browsers where navigator.onLine is implemented to spec, it doesn't apply to the situation where the remote API is unavailable. The decision has therefore been made to allow the application to decide what is considered "offline". Typically, this is implemented as a status of 0 as opposed to the server response of the 400-500 range.

Methods

value = offline.get(key, expunge)

Retrieves a previously stored value, optionally removing stale data.

Arguments

Returns

offline.set(key, value, expiry)

Stores the key-value pair with a freshness time limit.

Arguments

isFresh = offline.fresh(key)

Tests the expiration of the data. Returns false if the value is stale or missing.

Arguments

Returns

offline.expire(key)

If still fresh then marks the data as now expired.

Arguments

offline.remove(key)

Removes the data stored at key.

Arguments

offline.flush(prefix)

Removes all data with the given key prefix.

Arguments

offline.enableWarnings(enabled)

Enables or disables log warnings on quota or insertion errors.

Arguments

hasLocalStorage = offline.supported()

Tests the support of localStorage.

Returns

Unit Tests

Run the unit tests.

License

offline.js is licensed under the Apache License, Version 2.0.
Copyright © 2013, Stephen M. McKamey.

offline.js is a derivative work of lscache which is also licensed under the Apache License, Version 2.0.
Copyright © 2011, Pamela Fox.