Cookie common front end and caching technologies and localStorage sessionStorage and ApplicationCache

1、Cookie

JavaScript is a script running on the client, and therefore is generally not able to set Session, because Session is running on the server side. The cookie is running on the client, so you can use JS to set the cookie.

cookie structure: Simply put, cookie is stored in the form of key-value pairs, that is key = value format. Between each cookie is a general ";" to separate.

A cookie is a mechanism provided by the browser, cookie property will document object available to JavaScript. It can be controlled by JavaScript, but JavaScript is not nature itself. A cookie is stored on a user's hard drive file, which usually corresponds to a domain name, when the browser visits this domain again, this will make the cookie available. Therefore, cookie can span multiple pages in a domain name, but can not span multiple domains are using. 

The information stored in the cookie mechanism user's hard drive, it can be used as a global variable, which is its biggest advantage. It can be used for several applications. 

(1) to save the user logged on. (2) to track user behavior. (3) customized page. (4) create a shopping cart, for example, Taobao on the use of cookie records the user has visited merchandise, at any time convenient for comparison. 

cookie can complete part of the application, and many more features require global variables. Shortcoming cookie focused on security and privacy protection. Mainly include the following: 

(1) cookie may be disabled. When the user attaches great importance to the protection of personal privacy, he is likely to disable the cookie function browser; 
(2) cookie associated with the browser. This means that even if access to the same page, the saved between different browsers cookie is not accessible to each other; 
(3) cookie may be deleted. Because each cookie is a file on the hard disk, so the user is likely to be deleted; 
(4) cookie safety is not high enough. All of the cookie are recorded in the form of plain text in the file, so if you want to save information such as user name and password, the best pre-encrypted. 

 

JS setting cookie:

 

A page is assumed to be saved in the value of the variable username ( "jack") a cookie, key value name, the corresponding code JS:

document.cookie = ‘name = ’+ username;

 

Copy the code
JS read cookie: 

content stored in a cookie is assumed: name = jack; password = 123 

is acquired in the page B variable username JS code value is as follows: 

var = document.cookie.split username ( ";") [0 ] .split ( "=") [. 1]; 

! // cookies operating method of the JS 

// write cookies 

function the setCookie (name, value) 

{ 

var = 30 Days; 

var = exp new new a Date (); 

exp.setTime (exp. the getTime () + 60 Days * 24 * * 60 * 1000); 

the document.cookie = name + "=" + Escape (value) + "; Expires =" + exp.toGMTString (); 

} 

reading Cookies 

function the getCookie (name ) 

{ 

var ARR, the RegExp new new REG = ( "(^ |)" + name + "= ([^;] *) (; | $)"); 

IF (ARR = document.cookie.match (REG)) 

return unescape (ARR [2]); 

the else 

return null;

} 

 

Delete cookies

function delCookie(name)

{

var exp = new Date();

exp.setTime(exp.getTime() - 1);

var cval=getCookie(name);

if(cval!=null)

document.cookie= name + "="+cval+";expires="+exp.toGMTString();

}
Copy the code

 

The complete code

Copy the code
// If necessary to set custom expiration, then the above function into the following two functions setCookie on OK; 

function setCookie (name, value, Time) { 

    var strsec = GETSEC (Time); 

    var new new a Date = exp ( ); 

    exp.setTime (exp.getTime () * + strsec. 1); 

    the document.cookie = name + "=" + Escape (value) + "; Expires =" + exp.toGMTString (); 

} 

 

function the getCookie (name) { 

    var ARR, the RegExp new new REG = ( "(^ |)" + name + "= ([^;] *) (; | $)"); 

    IF (ARR = document.cookie.match (REG)) 

        return unescape (ARR [2]); 

    the else 

        return null; 

} 

 

function delCookie (name) { 

    var = exp new new a Date (); 

    exp.setTime (exp.getTime () -. 1); 

    var = CVAL the getCookie (name);

    if (cval != null)

        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();

}

 

function getsec(str) {

    alert(str);

    var str1 = str.substring(1, str.length) * 1;

    var str2 = str.substring(0, 1);

    if (str2 == "s") {

        return str1 * 1000;

    } else if (str2 == "h") {

        return str1 * 60 * 60 * 1000;

    } else if (str2 == "d") {

        return str1 * 24 * 60 * 60 * 1000;

    }

}

setCookie("name", "hayden");

alert(getCookie("name"));
// D is the number of days, 30 days is: d30
@ H refers to hours, eg 12 hours is: H12
// S20 represent 20 seconds

Set // This is an example of the use of expiration time:




setCookie("name", "hayden", "s20");
Copy the code

2、localStorage

First, what is localstorage?

In HTML5, the new joined a localStorage feature, this feature is mainly used to be used as a local storage, to solve the problem of shortage of storage space cookie (cookie cookie in each storage space for 4k), localStorage general browser support is 5M size, this localStorage will be different in different browsers.

Two, localstorage advantages and limitations

localStorage advantage

1, localStorage expand the 4K limit the cookie

2, localStorage will be the first time the requested data is stored directly to a local, this is equivalent to a size of only 5M high version of the browser for the front page of the database, compared to the cookie can save bandwidth, but this is in only in support of

localStorage limitations

1, the size of the browser is not uniform, and it supports localStorage this property in more than IE8 IE versions

2, all current browsers will put localStorage value type is defined as a string type, this conversion takes some of us everyday more common JSON object type

3, localStorage in the browser's privacy mode following is unreadable

4, the localStorage is essentially a reading of the string, if the stored content and more words will consume memory space will cause the page to change card

5, localStorage crawler can not be crawled

The only difference is that localStorage localStorage and sessionStorage belong to permanent storage, and sessionStorage belong when the session ended, sessionStorage key-value pairs will be cleared

 

Three , localstorage use

It must declare what, if you are using IE browser, then we should be as a UserData store, here is mainly on localStorage content, so userData do not do too much explanation, but also to bloggers personal opinion, there is no UserData need to learn to use, because the current IE6 / IE7 are out of position, and in many of today's page development will involve emerging technologies HTML5 \ CSS3, etc., so in general we will not go above using it be compatible

First, when using localStorage, we need to determine whether the browser supports localStorage this property

Copy the code
IF (! window.localStorage) { 

      Alert ( "Browser Support localStorage"); 

      return to false; 

} the else { 

     // main business logic 

} 

writing localStorage, the write localStorage in three ways 

if (window.localStorage!) { 

            alert ( "browser support localStorage"); 

            return to false; 

        } the else { 

            var = Storage window.localStorage; 

            // write a field 

            Storage [ "a"] =. 1; 

            // b writing field 

            storage.a = 1; 

            c // write field 

            storage.setItem ( "c",. 3); 

            the console.log (typeof Storage [ "A"]); 

            the console.log (typeof Storage [ "B"]); 

            Console.log(typeof storage["c"]);

 }
Copy the code

 

Here we must explain the use of localStorage also follow the same origin policy, so different websites can not directly share the same localStorage

Note: The storage into an int, but the print is of type string, and this characteristic localStorage itself relevant, localStorage only supports string type of storage.

 

localStorage read

 

Copy the code
IF (! window.localStorage) { 

            Alert ( "Browser Support localStorage"); 

        } the else { 

            var = window.localStorage storage; 

            // write a field 

            storage [ "a"] =. 1; 

            // b writing field 

            storage =. 1 II.A; 

            // write field c 

            storage.setItem ( "c",. 3); 

            the console.log (typeof Storage [ "A"]); 

            the console.log (typeof Storage [ "B"]); 

            Console. log (typeof Storage [ "C"]); 

            // read the first method 

            var A = storage.a; 

            the console.log (A); 

            // read the second method 

            var b = storage [ "b" ] ; 

            the console.log (B);

            // third method reading

            var c=storage.getItem("c");

            console.log(c);

        }
Copy the code

 

There are three reading of localStorage, where the official recommendation is getItem \ setItem these two methods to access them, do not ask me why, because I do not know this

LocalStorage is what I said before the equivalent of a front-end database, the database mainly additions and deletions to change search these four steps, where the increase is equivalent to reading and writing, check these two steps

Here we have to talk about delete localStorage, and change these two steps

This step change is better understood, again with the idea of ​​changing the value of a global variable, as here we are with a simple example to explain

Copy the code
IF (! window.localStorage) { 

            Alert ( "Browser Support localStorage"); 

        } the else { 

            var = window.localStorage storage; 

            // write a field 

            storage [ "a"] =. 1; 

            // b writing field 

            storage =. 1 .B; 

            // write field c 

            storage.setItem ( "c",. 3); 

            the console.log (storage.a); 

            // the console.log (typeof Storage [ "A"]); 

            // Console. log (typeof Storage [ "B"]); 

            // the console.log (typeof Storage [ "C"]); 

            / * dividing line * / 

            storage.a =. 4; 

            the console.log (storage.a); 

        }
Copy the code

 

The console above we can see that a key has been changed to a 4

Delete the localStorage

Copy the code
1, all the contents of the clearing localStorage 

var = Storage window.localStorage; 

            storage.a = 1; 

            storage.setItem ( "C",. 3); 

            the console.log (Storage); 

            storage.clear (); 

            the console.log (Storage ); 

2, of a key-value in the localStorage deletion 

var = Storage window.localStorage; 

            storage.a =. 1; 

            storage.setItem ( "C",. 3); 

            the console.log (Storage); 

            storage.removeItem ( " A "); 

            the console.log (storage.a);
Copy the code

 

 

localStorage key acquisition

Copy the code
var storage=window.localStorage;

            storage.a=1;

            storage.setItem("c",3);

            for(var i=0;i<storage.length;i++){

                var key=storage.key(i);

                console.log(key);

            }
Copy the code

 

Use key () method, access thereto to obtain a corresponding key index.

Four, localstorage Other Considerations

Generally, we will JSON stored in localStorage, but localStorage localStorage will automatically be converted into a string

This time we can use JSON.stringify () This method, to be converted into JSON JSON string

Example:

Copy the code
if(!window.localStorage){

            alert("浏览器支持localstorage");

        }else{

            var storage=window.localStorage;

            var data={

                name:'xiecanyong',

                sex:'man',

                hobby:'program'

            };

            var d=JSON.stringify(data);

            storage.setItem("data",d);

            console.log(storage.data);

        }
Copy the code

 

After reading To JSON string it converted into JSON object using the JSON.parse () method

Copy the code
Storage window.localStorage = var; 

            var {Data = 

                name: 'xiecanyong', 

                Sex: 'man', 

                Hobby: 'Program' 

            }; 

            var D = the JSON.stringify (Data); 

            storage.setItem ( "Data", D) ; 

            // JSON string converted into target output JSON 

            var = storage.getItem JSON ( "Data"); 

            var = jsonObj the JSON.parse (JSON); 

            the console.log (typeof jsonObj);
Copy the code

3、sessionStorage

sessionStorage a local storage for data session (session) of these data only in the same page in order to access a session and after the session ends data also will be destroyed. So sessionStorage not a persistent local storage, only the session-level storage. Here is its usage:

 

Copy the code
<! DOCTYPE the HTML> 

<HTML> 

<head> 

    <Meta charset = "UTF-. 8"> 

    <title> sessionStorage </ title> 

    <Script type = "text / JavaScript"> 

    the window.onload = function () { 

        // First the obtained body 3 input element 

        var msg = document.getElementById ( "msg" ); // the contents of the text box to enter 

        var getData = document.getElementById ( "getData" ); // get the data 

        var setData = document.getElementById ( "setData"); // save data 

        var removeData = document.getElementById ( "removeData" ); // removable data 

        setData.onclick = function () // logging data 

            { 

                IF (msg.value) { 

                    the sessionStorage.setItem ( "data", msg.value); // save data value corresponding to sessionStorage

                    alert ( "information has been saved into the data field"); 

                } the else { 

                    alert ( "message can not be empty"); 

                } 

            } 

        getData.onclick = function () { 

            // Get Data 

            var msg = sessionStorage.getItem ( "data" ); 

            IF (MSG) { 

                Alert ( "data field is:" + msg); // data corresponding to the value pop 

            } the else { 

                "! no value data field" Alert (); 

            } 

        } 

        removeData.onclick = function () // removable data 

            { 

                var = sessionStorage.getItem MSG ( "data"); 

                sessionStorage.removeChild (MSG);

            }

    }

    </script>

</head>

 

<body>

    <input id="msg" type="text" />

    <input id="setData" type="button" value="保存数据" />

    <input id="getData" type="button" value="获取数据" />

    <input id="removeData" type="button" value="移除数据" />

</body>

</html>
Copy the code

Another point to note is that other types of reading out should be converted.

 

4、ApplicationCache

 

applicationCache html5 is a new offline application functionality

• Offline Browsing: Users can browse the offline website content.
• faster: because the data is stored locally, so the speed will be faster.
• reduce the load on the server: The browser will only download resources changed on the server.
Need a manifest file at the time of application caching,

 

cache manifest format is
the first line must be CACHE MANIFEST
next can be divided into three sections: CACHE, NETWORK, and FALLBACK
CACHE: This is the default paragraph cache file record belongs to. In CACHE: After paragraph title (or with direct line after the CACHE MANIFEST) lists the files will be cached after they are first downloaded. NETWORK: In NETWORK: section headings listed in the white list is the need to file resource connection to the server. All requests similar resources will bypass the cache, even if the user is offline. You can use wildcards. FALLBACK: FALLBACK: section defines a back-page, when the resource can not be accessed, the browser will use this page. Each record in this paragraph are listed first two URI- represent resources, the second one is a backup page. Two URI must use relative paths and homology with the manifest file. You can use wildcards.
CACHE, NETWORK, and FALLBACK paragraph may appear in any order in the cache manifest file, and each paragraph may appear more than once in the same manifest file.

 

applicationcache/

 

├── static/

 

│   ├── css/

 

│   │ └── example.css

 

│   └── js/

 

│     └── example.js

 

└── index.jsp

 

 

 

#code show as below

 

#example.css

 

#clock {font: 2em sans-serif; }

 

 

 

#example.js

 

window.onload = function(){

 

          window.onload = function(){

 

            setInterval(function(){

 

                      document.getElementById('clock').innerHTML = new Date();

 

            },1000);

 

  };

 

};

 

 

 

#index.jsp

 

<link type="text/css" href="static/css/example.css" rel="stylesheet"/>

 

<script src="static/js/example.js"></script>

 

<div id="clock"></div>

 

We add new artifacts manifest file html5

 

Add in the static file folder, file reads as follows

 

#example.manifest

 

CACHE MANIFEST

 

./js/example.js

 

../index.jsp

 

NETWORK:

 

./css/exmaple.css

 

Then you need to modify the contents of the file index.jsp

 

<html> --> <html manifest="static/example.manifest">

 

Js and jsp file description of the cache, and css files are included in the white list is not cached, start the service again. . . .

When you visit a page that did not see any change, the page with the first visit of a bird-like, but you press the F12 will see the file browser has cached a pair of

 

In resources-> application under cache options you can see the browser cache of what stuff, you can also use chrome: // appcache-internals / delete command to view in the Chrome browser.

 

Well ** miracle of the moment arrived, I again stopped the service. . . . . . Visit again, was able to visit, not like the first time that prompted hung up.

 

But not the style. . . That's just the style we set the white list, no cached

if your manifest file is modified, you can update it manually or automatically
1. Automatic update your browser to access the Web application except once in the first cache outside resources, only It will update the cache when the cache manifest file itself is changed. The resource file cache manifest in changes and will not be updated. 2. Manually update Developers can also use the interface to update the cache window.applicationCache. The method is the detection value window.applicationCache.status, if it is UPDATEREADY, you can update the cache call window.applicationCache.update (). Sample code below. 


 

 

if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {

 

  window.applicationCache.update();

 

}

 

applicationCache state value

 

Uncached (not cached) a special value used to indicate that an application has not been fully initialized cache object.

 

IDLE (idle) at this time is not in the application cache update process.

 

CHECKING (check) list has been acquired complete and check for updates.

 

DOWNLOADING (download) Download Resources and ready to be added to the cache, which is due to changes in inventory due.

 

UPDATEREADY (update-ready) a new version of the application cache can be used. There is a corresponding event updateready, when finished downloading an update, and yet use swapCache () method is activated when updating the event triggers, and events will not be cached.

 

OBSOLETE (abandoned) application cache is now obsolete.

 

Online status can also detect

1.navigator.onLine navigator.onLine attribute indicates whether the current line. If true, it indicates online; if false, means that offline. When the network status change navigator.onLine value also changes. Developers may obtain network state by reading its value. 2.online/offline event when developing off-line applications, access to network status by navigator.onLine usually is not enough. Developers also need to be notified immediately when changes occur in the network state,  HTML5  also provides online / offline events. When an online / offline switching, online / offline events will trigger on the body element, and bubbling the order along document.body, document, and the window. Therefore, developers can monitor their online / offline events to learn network status. 


 

Guess you like

Origin www.cnblogs.com/Children-qiuzhen/p/11597401.html