Client side ajax caching using Smartjax.js to improve the UX.
Any need for ajax caching?
Probably it depends on the application; or may be on that ajax call itself, if it should be cached or not. Lemme describe it with some example scenarios:
Same info in different widgets / components.
Suppose you have two different web components or widgets who for some reason uses the same api call. So rather than making two different calls, or putting efforts to handle the response from any parent component or by events, it’s better to cache the response of the call.
Repetitive occurrence of the same widget / component
If a widget or web component (suppose the user info widget which displays the details of the logged in user at the top of every page) is appearing in every page (or most of the pages) of your application and it’s using the same api call again and again, then we can think of caching.
Suppose a hotel booking site is there where you’ve searched for hotels in an area and it throws you 10 itineraries in the results page with pagination. So if you click on page `3` and an ajax call is fired to get results. Now after getting those results you decided to go back again to page `1`. Then the ajax will be fired again. So if we’d cached the the response of page `1` before, we could have skipped the call.
Fast second load
The second load of a page is generally faster as the browser caches the static files. Now if you also cache the ajax calls in `sessionStorage` level, your user don’t have to wait at all for any kind of server interaction rather than the document response.
Benefits of Smartjax
Smartjax allow you to cache your ajax calls in a handsome way with more control on saving and deleting. It uses jQuery’s `$.ajax()` method internally to make ajax calls. If you were also making calls using `$.ajax()` in your application, you can just replace the `$.ajax` with `Smartjax.ajax` and rest will be taken care of by the plugin.
Smartjax is not doing any rocket science. It’s simply a service which makes the ajax calls for you, cache it and return you the same response if called second time. Below are the features in the caching service of Smartjax.
- Cache any call you want.
- Clear on demand.
- Clear a group of calls.
- If a call is fired and not resolved yet, but some other component also fired the same call; smartjax smartly return the first promise to the second caller without making a new call, even if it didn’t find the response in the store.
- Caching by levels: page level, tab level and forever level. The name of the level represents the lifespan of the cached data.
How to use
Learning curve of this light weight plugin is very low or almost nil. You can visit the github page to read the syntax and detailed uses.