The front end skillfully uses localstorage to do "cache", reduces the number of HTTP requests

Source: Internet
Author: User

Scene:

Loading a page, JS needs to get some data through Ajax request

So every time you refresh the page there is a request, if the data on the real-time requirements are not high, obviously this is not advisable.

How to reduce the pressure on the service side, using Localstorage can solve this problem.

Suppose the ID is part of the other K value to be stored.
var flag=0,k=null,v_arr=[],v_time=0,v= ';
var cday = new Date (). GetDate ();
var k = Window.localStorage.getItem (' name_ ' +id);
if (k!== null) {
V_arr = K.split ("@");
V_time = v_arr[1];
Day expires
if (cday! = v_time) {
flag = 1;
} else {
flag = 2;
v = v_arr[0];
Take the value of V and do the right thing.
}

}
if (Flag < 2) {
Initiating a request
$.ajax (
Xx
Xxx
    Success:function (data) {
Stores data valid values.
Window.localStorage.setItem (' name_ ' +id,data.id+ ' @ ' +new Date (). GetDate ());
       Take the value of V and do the right thing.

});


}

The front end skillfully uses localstorage to do "cache", reduces the number of HTTP 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.