Application State - HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

5 - Application State

A session state is created when a user first requests access to an application, and it ends when the session closes, such as when a user logs off.

An application state exists from the time a Web browser requests a Web page until the browser closes. Persistent state information is data that exists after a session ends. In HTML5, developers can use the localStorage and sessionStorage JavaScript methods to deal efficiently with state data. In addition, AppCache enables a user to load data ordinarily stored on a server even when the user is offline.

Storing State Data Using Local and Session Storage

When we enter a uniform resource locator (URL) into the address bar of a browser, the browser sends an HTTP request to a Web server for a Web page.

HTTP is short for Hypertext Transport Protocol. HTTP is a stateless protocol, which means that it doesn’t retain data from session to session.

Therefore, when we close a Web browser after using an application, data is not automatically saved.

To work around the limitations of HTTP protocol, developers historically have used cookies, which are small files that contain information about the user and the Web site visited and are saved on the user’s computer. When a user returns to a visited site, the browser sends the cookies back to the Web server. Cookies help a Web server “remember” a user and customize the user’s experience on that site.

However, cookies have proven to be a security risk. In addition, if large amounts of data are involved, all the data gets sent between the browser and server upon every request, which would cause a noticeable performance decrease to the user.

In HTML5, developers can use the Web storage instead, which offers more flexibility, larger data sets, and better performance. The localStorage method allows users to save larger amounts of data from session to s ession (persistent data), and there’s no time limit as to how long the data exists.

The SessionStorage method keeps data only for one session (until the browser is closed), which is also referred to as “per-tab storage.” Using these methods, specific data is transferred only when requested, so it’s possible to store a relatively large amount of data without slowing down the connection or site.

Appcache for offline files

Another way to use Web storage is to store data locally when a user is offline. The Application Cache, or AppCache, stores resources like images, HTML pages, CSS files, and JavaScript - data that would ordinarily be stored on a server. Because the resources are stored on the client’s hard disk or device, the resources load faster when requested.

Using AppCache, a developer uses a text file called a “cache manifest” to specify the files a Web browser should cache offline. Even if a user presses the Refresh button offline, the app will load and work correctly.