[Open source]jquery-ajax-cache: Quickly optimize page Ajax requests, using Localstorage cache requests

Source: Internet
Author: User
Tags sessionstorage

  Project: Jquery-ajax-cache

Address: Https://github.com/WQTeam/jquery-ajax-cache

A cache of local cache Localstorage was recently used in the project to do the data.

1, simply say Localstorage

Localstorage and Cookies store more capacity in the browser than they do. In addition, the biggest feature is not to be attached to the HTTP request in the background, and will not be like cookies caused by the HTTP head to affect the transmission performance. For this reason, Localstorage is suitable for caching some commonly used data, without the need for trivial data requests like the background.

The Localstorage API is very simple to reference

Two common methods SetItem and GetItem

  

Localstorage.setitem (key, value); Locastorage.getitem (key); return value

  

Because the stored content is of type string. When the JS object needs to be saved. The JS object needs to be converted to string first. The method is also very simple json.stringify, the corresponding use json.parse when removed

2. How to use Localstorage in the project

  The biggest difference between localstorage as a front-end storage and a database in the background is that this kind of storage is unreliable. Users can clear the browser cache at any time, and other browser- free browsing modes will disable Localstorage. So it's best to use a cache that's optimized for performance rather than localstorage the data. But as the cache Localstorage is too simple to set the timeout time, another project has expanded for this: Web-storage-cache.

3. There is no better way to use it in practice

In the project to do performance optimization, we all want to optimize the way is not to affect the original code, not add new code logic.

Assuming that there is a segment of data in a business scenario that is used in multiple places, the most straightforward approach is to:

  

var data = Localstorage.getitem (' CacheKey '); if // if data is empty, make a request $.ajax ({   ' xxxx ',   function(response) {
if (Response.code = = = 1) { //success!
Loccalstorage.setitem (' CacheKey ', response.data);
} // other business processing ... }})

If the interface design is unified, you can encapsulate your own Ajax method, intercept the request

functionMyajax () {vararg = Arguments[0]; varRealsuccess =arg.success; varRealbeforesend =Arg.beforesend; Arg.success=function(response) {if(Response.code = = 1) {Localstorage.setitem (CacheKey/*you need to generate a different key based on the request parameters*/, Response.data); } realsuccess&& realsuccess.apply (NULL, arguments); } $.ajax (ARG);}

As in the above code, the same can increase the Beforesend interception request to determine whether to read in the cache. This makes the business logic less affected.

4, jquery itself supports the expansion of Ajax methods

This is the way most people use it, but in fact jquery provides a better way to extend Ajax. The two methods of $.ajaxprefilter and $.ajaxtransport can better intercept. The Jquery-ajax-cache plugin is also used in this way.

I am interested in the standard ES2015 and webpack, so this open source project is useful.

5, about Jquery-ajax-cache

  The Jquery-ajax-cache plugin extends the jquery $.ajax , providing a very convenient way to cache Ajax requests into ' localstorage ' or ' sessionstorage '. The only thing you have to do is implement the cacheValidate method and verify that the return result requires caching. Page loading and data reading and writing process plug-ins will be out of date data cleanup, to avoid the accumulation of outdated data. You can also invoke $ajaxCache.deleteAllExpires() manual purge of expired caches.

  Global configuration

$ajaxCache. config ({    //  business logic to determine if the request is cached, RES is the Ajax return result, options are $.ajax parameters     function (res, options) {    // Optional, configure global validation for the method that requires caching, "global Configuration" and "Custom", at least one place to implement the Cachevalidate method        return res.state = = = ' OK ';    }    ,// optional, ' localstorage ' or ' Sessionstorage ', default ' Localstorage '    // optional, per second. Default 1 hours });

Simple and practical

$.ajax ({    //  used whenever adding a single line to an AJAX request   Ajaxcache:true    true     //  "Global Configuration" and "Custom", there is at least one place to implement the Cachevalidate method/    *     others ...     */ });

 Custom

$.ajax (//The parameters here override the settings in ' Global configuration 'Ajaxcache: {//The business logic determines whether the request is cached, the res is the Ajax return result, and options is the $.ajax parameterCachevalidate:function(Res, options) {//Optional, configure global validation to see if caching is required, "Global Configuration" and "Custom", at least one place to implement the Cachevalidate method            returnRes.state = = = ' OK ' && res.code = = = ' 200 '; }, Storagetype:' Localstorage ',//Optional, ' localstorage ' or ' sessionstorage ', default ' Localstorage 'TIMEOUT:60 * 60,//optional, unit seconds. Default 1 hours    }});

Due to the limited capacity of individuals, there are inevitably bugs that can be reflected in https://github.com/WQTeam/jquery-ajax-cache/issues

[Open source]jquery-ajax-cache: Quickly optimize page Ajax requests, using Localstorage cache requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.