Web Offline applications

Source: Internet
Author: User
Tags browser cache sessionstorage

In fact, the browser has always been the front-end developers to compare the headache of a topic, various compatibility. Until the beginning of normalization and standardization, the advent of HTML5.

In the absence of this set of standards before the issue of client-side caching, we basically use cookies processing, of course, in addition to the background management type of software, front-facing is still in the use of cookies, after all, there are still many antiques are still using IE and the old browser version.

The two global objects, Localstorage and Sessionstorage, are the newly proposed Web storage standards. In fact, both are the same persisted array object, the difference is the validity period of its storage and the difference of its use.

                expiry date access Rights           

  localstorage remains in effect unless you actively delete the document source permission

  sessionstorage Browser window, tab document source permissions, and is the same window (label)

* * Document source permissions, i.e. must protocol (http://), hostname (gabin.top), port (80) are consistent to be shared

It is important to note that both are indexed by strings and are stored with strings. In other words, if you use

Localstorage.cache = {One:1}

Localstorage.cache is still an empty string and is serialized and deserialized only through the two methods of Json.parse and Json.stringify. We can operate normally.

These two objects also provide a more formal API

    • SetItem (key, value)
    • GetItem ()
    • Clear () This method must be used with caution, will delete all cache information, add stored data without backup, will be lost

Event:

Onstorage: When data is stored at different window levels or in different windows (Localstorage), it will be broadcast.

################################################

Here is the application cache

################################################

Applicationcache object, currently I can't get the index of this global object in the latest version of idea, but under Chrome, it's really available.

Unlike the previously mentioned Web Store, Applicationcache is more like a program installation package than a cache, which is not deleted as it clears the browser cache.

In fact, I was writing this book the day before it took a few hours, but also stayed up to write a demo. To tell you the truth, I don't know that much. Just the project needs research, so did the next study.

The application cache is basically made up of a list, presumably like this:

  

1.0.9# When you enter a page with this list link, the cached content will start # no absolute path is relative to the manifest file's relative path CACHE:permanote.html/static/jquery/ jquery-1.8.0. jspermanote.jsfallback:# below each line is two values, separated by a space, the previous address will try to get the network, and will not be available when the second cache instead of http://  Ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js/static/jquery/jquery-1.8.0.jsNETWORK:# The address below will be networked to get /cache/note

The header of the file begins with the CACHE manifest, and the generic file suffix is. appcache

Cache: Indicates that the following URLs are cached locally

FALLBACK: Indicates that the network will be acquired first, if the cached data of the backup is not taken instead

Network: Indicates access only via networking

(* There is a reference to the need for the server to return. appcache file Mine-type with Text/cache-manifest, but the visual I did not use, and later encountered this problem to fill up)

Now we are missing an access page:

<!DOCTYPE HTML><HTMLLang= "en"Manifest= "/static/cache/note/permanote.appcache"><Head>    <MetaCharSet= "UTF-8">    <title>Application Cache Example-Notepad</title>    <Scriptsrc= "/static/jquery/jquery-1.8.0.js"></Script>    <Scriptsrc= "Permanote.js"></Script>    <style>#editor{width:100%;Height:250px;        }#statusline{width:100%;        }    </style></Head><Body>    <DivID= "Toolbar">        <ButtonID= "Savebutton">Save</Button>        <ButtonID= "SyncButton">Syncing notebooks</Button>        <ButtonID= "UpdateButton">Update offline programs</Button>    </Div>    <textareaID= "Editor"></textarea>    <DivID= "Statusline"></Div></Body></HTML>

Permanote.js:

(function($) {    varEditor, Statusline, Savebutton, SyncButton, UpdateButton, idletimer, localstorage =Window.localstorage; Window.onload=function() {        //Initialize local storage when initializing for the first time        if(Localstorage.note = =NULL) {Localstorage.note= ""; }        if(Localstorage.lastmodified = =NULL) {localstorage.lastmodified= 0; }        if(localstorage.lastsaved = =NULL) {localstorage.lastsaved= 0; } Editor= $ ("#editor"); Statusline= $ ("#statusline"); Savebutton= $ ("#saveButton"); SyncButton= $ ("#syncButton"); UpdateButton= $ ("#updateButton");        Editor.val (Localstorage.note); Editor.attr ("Disabled",true);//prohibit editing before synchronizing        //once the text area has content inputEditor.bind ("Input",function(e) {//Save the new value in LocalstorageLocalstorage.note =Editor.val (); Localstorage.lastmodified=Date.now (); //Reset Idle Timer            if(Idletimer) window.cleartimeout (Idletimer); Idletimer= SetTimeout (Save, 5000); //Enable save buttonSavebutton.removeattr ("Disabled");        }); Savebutton.bind ("Click", save); Syncbutton.bind ("Click", sync); Updatebutton.bind ("Click",function() {applicationcache.update ();        }); //try synchronizing the server each time you load the applicationsync (); }    //save data to server before leaving pageWindow.onbeforeunload =function() {        if(Localstorage.lastmodified >localstorage.lastsaved) {save (); }    }    //notifies the user when offlineWindow.onoffline =function() {Msgstatus (Offline); }    //when you return to the online state again, synchronizeWindow.online =function() {sync (); }    //notify users when a new version is available    //can also be forced to reload, Location.reload ();Window.applicationCache.onupdateready =function() {Msgstatus ("Updating new version ...");    Location.reload (); }    //notify the user when no new version is availableWindow.applicationCache.onnoupdate =function() {Msgstatus ("There are no updatable versions"); }    //whenever the note content is updated, if the user stops editing for more than five minutes,    //The note text is automatically uploaded to the server (in the online state)    functionSave () {if(Idletimer) {cleartimeout (Idletimer); } Idletimer=NULL; if(navigator.online) {$.post ("/cache/note", {Note:editor.val ()},function() {localstorage.lastsaved=Date.now (); Savebutton.attr ("Disabled",true);        }); }    }    //Check if the server has a new version of notes    //if not, save the current version to the server side    functionsync () {if(navigator.online) {$.get ("/cache/note",function(data) {varRemotemodtime = 0; Remotemodtime= data["Last"]; Remotemodtime=NewDate (remotemodtime). GetTime (); if(Remotemodtime >localstorage.lastsaved) {msgstatus ("Discover what needs to be updated"); varUseit = Confirm ("Whether to replace current data with new version content")                    varnow =Date.now (); if(Useit) {localstorage.note=Data.data;                        Editor.val (Data.data); Localstorage.lastsaved=Now ; Msgstatus ("The latest data has been downloaded"); }                } Else{msgstatus ("No new data found"); }                if(Localstorage.lastmodified >localstorage.lastsaved) {save (); } editor.removeattr ("Disabled");//Enable editor againEditor.focus ();        }); } Else{//offline state, cannot be synchronizedMsgstatus ("Offline status, synchronization failed"); Editor.removeattr ("Disabled");//Enable editor againEditor.focus (); }    }    functionmsgstatus (status) {Statusline.text (status); }} (JQuery));

The result of the visit is this:

The server's code is probably like this:

 Private StaticString Note = ""; Private StaticDate lastmodify; @RequestMapping (Value= "/note", method =requestmethod.post) @ResponseBody PublicMap<string, object>Note (String Note) { This. Note =Note; if(Note! = This. Note) {lastmodify=NewDate (); } Map<string, object> successmap =Renderutils.getsuccessmap (); Successmap.put ("Data", note); returnSuccessmap; } @RequestMapping (Value= "/note", method =requestmethod.get) @ResponseBody PublicMap<string, object>Note () {Map<string, object> successmap =Renderutils.getsuccessmap (); Successmap.put ("Data", note); Successmap.put ("Last", lastmodify); returnSuccessmap; }

Web Offline applications

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.