HTML and CSS Reference
In-Depth Information
Dynamically Choosing a Storage Engine
We now have two storage engines matching the requirements of our API, they can be used
entirely interchangeably (assuming the browser supports the underlying APIs). Our pre-
ferred approach is to use the IndexedDB storage engine if it is supported by the browser, and
to fallback to the Web storage API if it is not supported.
In order to load the correct storage engine we have two distinct tasks. The first is deciding
which storage engine we wish to use; the second is forcing that storage engine to load instead
of the other.
In order to determine if it is possible to use a particular storage engine we can use the fol-
if (window.localStorage) {
if (window.indexedDB) {
If the browser supports these APIs there will be a global property on the window object for
that API, and therefore the if statement will evaluate to true .
This approach is not foolproof, since there is nothing to stop us creating our own global
property called localStorage on the window object, but it is a quick and convenient mech-
anism that we can rely on if we are following good coding standards.
Now that we have an approach for determining if a particular storage engine is available,
we have several options for loading the correct storage engine at run-time. We will achieve
this through the use of AJAX. This will dynamically load the appropriate JavaScript file at
run-time based on the capabilities of the browser.
If you are not familiar with AJAX, you do not need to concern yourself with how
it works in this chapter. AJAX will be covered in depth later in the book .
To see how this works, delete both the storage engine imports:
<!--script src="scripts/tasks-webstorage.js"></script-->
<script src="scripts/tasks-indexeddb.js"></script>
And then replace the following in tasks.html:
Search WWH ::

Custom Search