Last active
April 28, 2018 05:04
-
-
Save jaredrada/7185419 to your computer and use it in GitHub Desktop.
jquery ajax localstorage cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $.ajaxPrefilter(function(options, originalOptions, jqXHR){ | |
| if(!options.ajaxCache) { | |
| return; | |
| } | |
| var cacheOptions = options.ajaxCache; | |
| var timeToLive = cacheOptions.timeToLive || 1000 * 60 * 60, //1hour | |
| cacheKey = cacheOptions.cacheKey || options.type + options.url, | |
| cached = JSON.parse(localStorage.getItem(cacheKey)); | |
| if( | |
| (!cached) //if cache does not exist | |
| || (cacheOptions.garbageCache) //if user wants new data | |
| || (cached.created + cached.timeToLive >= new Date().getTime()) //if cache is expired | |
| ) { | |
| //then remove the data, do a new ajax request, and store the result | |
| localStorage.removeItem(cacheKey); | |
| jqXHR.done(function(data){ | |
| var storageObj = { | |
| timeToLive : timeToLive, | |
| created : new Date().getTime, | |
| data : data | |
| }; | |
| localStorage.setItem(cacheKey, JSON.stringify(storageObj)); | |
| }); | |
| console.log('getting new data'); | |
| } else { | |
| //otherwise the data is still good, so return that | |
| //i'd like to manually resolve the deferred object here and create a "200" response code so everything downstream reacts normally | |
| jqXHR.status = 200; | |
| jqXHR.responseJSON = cached.data; | |
| jqXHR.abort(); //this breaks things, see if we can resolve deferred on our own? | |
| console.log('data is good'); | |
| console.log(jqXHR); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment