Giter VIP home page Giter VIP logo

jquery-ajax-localstorage-cache's Introduction

Jalc

jquery-ajax-localstorage-cache - abbreviated Jalc from here on, because the full name is a mouthful.

Jalc is a plugin built for jQuery (>= 1.5.1 for 1.x.x, and >=3.0.0 for 2.x.x) and any object implementing the storage interface, such as localStorage, providing a client-side cache for AJAX responses intended to save bandwith and time.

Versions tagged 1.x.x support jQuery 1.5.1+ up to jQuery version 3.0.0. Version 1.x.x is no longer receiving any updates, except bug fixes as needed.

Versions tagged 2.x.x support jQuery 3.0.0+.

Looking for a version that supports binary data (Blobs, ArrayBuffers)? Check out Jalic.

Looking for a version that offers caching for the new Fetch API? Check out fetchCache.

Bower

You can download and install this plugin using bower:

bower install jalc

You can also download the minified distribution version and install manually in your application: jalc.min.js.

Usage

Parameters

$.ajax({
    url: '/post',
    localCache: true,        // Required. Either a boolean, in which case localStorage will be used, or
                             // an object that implements the Storage interface.

    cacheTTL: 1,           // Optional. In hours. Can be used with float to indicate part of an hour, e.g. 0.5.
    cacheKey: 'post',      // optional.
    isCacheValid: function () {  // optional.
        return true;
    },
    isResponseValid: function (data, status, jqXHR) {  // optional.
        return data.code === '0';
    },
    thenResponse: function (data, status, jqXHR) { // optional, only in versions 2.x.x+
        // Alter data in whatever way you want it altered before it gets cached.
        data.code = 101;
        return data;
    }
}).done(function (response) {
    // The response is available here.
});

On your AJAX request you get 6 new parameters :

  • localCache
    • Turn localCache on/off, or specify an object implementing the Storage interface to use.
    • Default: false
  • cacheTTL
    • How long, in hours, the cached values should be considered valid.
    • Floats can be used to indicate some part of an hour, e.g. 0.5 to indicate half-an-hour.
    • Applies to cacheKey specified/calculated - each cached object will respect it's own cacheTTL, there is no 'global' TTL timer for all cached objects.
    • Default : 5 hours
  • cacheKey
    • CacheKey is the key that will be used to store the response in localStorage.
    • A callback function can also be used to return dynamically generated cacheKey. Ajax options are passed to this callback, but keep in mind that the function needs to return a stable cacheKey - that is, for a given set of parameters, the function should always return the same generated cacheKey.
    • Default: URL + TYPE(GET/POST) + DATA (coerced to string)
  • isCacheValid
    • This function must return true or false. On false, the cached response is removed.
    • Default: null
  • isResponseValid
    • This function must return a 'truthy' value (boolean, or coercable to boolean). On falsey, the response from the server is not cached.
    • Default: null
  • thenResponse
    • This function must return the data to be passed on to the next then or done block. Allows you to specify a function which will alter the data in some way before caching it and returning it. Keep in mind that this function will NOT be called when fetching from the cache, only when fetching from remote, so don't rely on it to perform a transformation that you want to occur every time you make the ajax call - those should instead go in a then block on your ajax request.
    • Default: null

Notes

  • You can delete the cache by using localStorage.clear(), or by using localStorage.removeItem('cacheKey') if you specified a cacheKey. Note the above assumes you're using localStorage - replace as appropriate with your Storage interface implementing object.
  • You can pre-load content with this plugin. You just have do to an initial AJAX request with the same cacheKey.
  • In most cases, you can rely on the 'intelligent guess' for the dataType jQuery ajax parameter, and leave off the dataType parameter, and the plugin will store the content type returned from the server alongside the data. However, you will get more consistent results if you explicitly specify the dataType in the ajax parameters.

License

This project is distributed under Apache 2 License. See LICENSE.txt for more information.

jquery-ajax-localstorage-cache's People

Contributors

basicallydan avatar bshelton229 avatar caleywoods avatar dguzzo avatar iryusa avatar mludv avatar nigelkibodeaux avatar paulirish avatar rafis avatar robink avatar sanemethod avatar shaqq avatar softwarespot avatar sunnokon avatar tronhammer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-ajax-localstorage-cache's Issues

Optionally, do not clear cache on AJAX error

I am using it for a hybrid desktop app and sometimes the client is offline. AJAX fails and the cache is cleared. It would be great to have an option to keep the earlier contents till a successful fetch happens.

Add to bower.io

I see there is a fork already submitted. Though this is old and out dated than yours. So perhaps it's worth adding?

unable to clone on drush make process

There has been a new Drupal core security update released and when building our drupal site using drush make the module fails to clone this repo.

Unable to clone jquery-ajax-localstorage-cache from
[error]
[email protected]:SaneMethod/jquery-ajax-localstorage-cache.git.

We have the module added to our profile.make file and the correct github link to clone from but the drush make command errors when trying to clone this repo.

Any help with this would be great

josh

Check if options.localCache is undefined before continuing

If the user includes the function on each page, but doesn't require each ajax request to be 'cached', then more than likely they will not include localCache in the ajax options. Therefore a check for undefined should perhaps be done before anything else.

Doesn't work with async=false

Yeah yeah, I realize synchronous requests are a anti pattern, but... well, they exist and are allowed by jQuery so... should be supported. I might hack together a solution.

Build a plugin

Hello

It would be much better if you could build a plugin for wordpress.

In wordpress, it is really a a headache to handle jquery.js when optimize the sites to improve faster speed for mobile mode, since there will lots of issue if make jquery.js deferred loading, but if not, the page loading speed will be slower, that might the reason why also google pagespeed insight suggest make it deferred loading

Maybe set jquery.js to be cached would be a good way to speed up page loading.

Thanks.

Alex

cacheKey sometimes generates poorly

Didn't have lots of time to investigate, but when using jQuery 1.11.3, genCacheKey() generates different keys when storing and getting the cached object and plugin doesn't work correctly.
That could be because of options.url difference in the function, in one place it looks like pure url, in other like url + params already.

Anyway thanks for your great work!

research prior art

so amplify has something like this

and for fucks sake someone else must have done this exact thing only better already.

i mean srsly.

Bug when cache is set to false and cacheKey omitted in the options

The fix is pretty trivial with a regex in genCacheKey(). The issue is because the timestamp is tacked on afterwards, so isn't present in the url the first time around.

    var genCacheKey = function (options) {
        var url = options.url.replace(/jQuery.*/, '');

        // Strip _={timestamp}, if cache is set to false
        if (options.cache === false) {
            url = url.replace(/\??_=\d{13}/, '');
        }

        return options.cacheKey || url + options.type + (options.data || '');
    };

'toLowerCase' error during ajax call.

Hi,

I am getting this error after ajax call.

Code :
$(function(){
$.ajax({
url : 'https://api.myjson.com/bins/wmg5',
localCache : true, // Required. Either a boolean, in which case localStorage will be used, or an object that implements the Storage interface.

    cacheTTL     : 1,           // Optional. In hours.
    cacheKey     : 'POST',      // optional.
    isCacheValid : function(){  // optional.
        return true;
    }
}).done(function(response){
    response.map(function(i,val){
        $('.container').append("<div>"+val.first_name+"</div")
    });
});

});

error :
image

Please help me to solve the issue.

Thanks

Doenst work with dataType XML

Hi,
thanks for this cool extension for $.ajax :)

But it doesnt work with dataType: "xml"
I get the following error:

Uncaught Error: Syntax error, unrecognized expression: [object XMLDocument]

Greetings

Edit
Does work if i use dataType: "html" and parse xml using $.parseXML(respond) afterwards
Maybe just add this to Notes :)

Success function array fails: TypeError: object is not a function

jQuery.ajax() API allows for an array of success functions to be specified:

As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn.

The following line is incompatible with this:

if ( options.realsuccess ) options.realsuccess( data );

Status code caching

In order to prevent jQuery from treating this differently in the statusCode property of ajaxSetup I think it might be useful to cache status codes with body.

I'm gonna do this on my own fork then make a pull request. The way I was gonna do it was to put it in a separate localStorage key. If anybody reading this has any thoughts of strong feelings against this, please say so.

default cacheKey function fails

The default cacheKey generation fails for GET requests because the options url/data pair is mutated between the call to ajaxPrefilter and ajaxTransport.

In ajaxPrefilter():

  • options.type = GET
  • options.url = /path/to/api/method
  • options.data = p1=param1&p2=param2

In ajaxTransport():

  • options.type = GET
  • options.url = /path/to/api/method?p1=param1&p2=param2&_=1489431445387
  • options.data = undefined

So the default cacheKey of (url + type + data) yields:
ajaxPrefilter => /path/to/api/methodGETp1=param1&p2=param2
ajaxTransport => /path/to/api/method?p1=param1&p2=param2GET

This cacheKey function works nicely for both GET and POST requests.
return options.type + url + (options.data ? '?' + options.data : '');

Error Checking on dataType

I got an error:
Uncaught TypeError: Cannot read property 'toLowerCase' of null
on this line:
if (dataType.toLowerCase().indexOf('json') !== -1) strdata = JSON.stringify(data);

This happens when both dataType and the content response headers are empty. (I do see though, a returned this.dataTypes array)

Perhaps directly check the type of data to know to stringify objects?
Or circumvent with a quick error check:
dataType && dataType.toLowerCase().indexOf('json') ...

Simple error check doesn't prevent possibly storing unstringified data.

Add seamless integration with ifModified jQuery's option

I'd like to request a feature if you have interest on implementing it.

What I'd really like is a plugin that would allow jQuery to automatically cache my responses when Last-Modified or ETag headers are set in the response.

When you set the ifModified option to true in the $.ajax options, jQuery will fill in the if-modified-since header for instance. But the main problem is that it won't cache the result of a request with a Last-Modified header present. That means the next time you make the ajax call, data will be undefined if the server responds with 304 (Not Modified).

If your plugin could automatically detect when Last-Modified or ETag is sent by the server and cache the result so that it is used in 304 responses transparently, then the caching would work seamlessly with no code changes in the sense that the ajax handlers will get the cached data in the arguments instead of undefined.

In the seamless mode, no cache is performed by the plugin unless Last-Modified or ETag is present in the header.

What do you think? Does it make sense?

Unmaintained

I haven't touched this project in years. If anyone wants to take on ownership, please email me.

Otherwise, you should probably avoid it. :)

window is not scoped

; (function($, window, undefined) {

Something like this is recommended. I am not submitting as a PR, until I know you're okay with this.

Support for deferred chaining

My demo isn't working, maybe no localstorage in iframes ? http://jsfiddle.net/ZFexL/1/

However based on the source, I don't think getting deferred ajax results from the cache will work using jQuery.ajaxPrefilter as it fires asychronously, though I could be wrong...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.