From Wep page to Application, wepapplication

Source: Internet
Author: User
Tags sessionstorage

From Wep page to Application, wepapplication

You need to make a choice, whether it is a Web app or a Native app, of course, there is a third type, Hybrid app.

Nowadays, there are more and more mobile phone users, and computer terminal browsers are constantly being updated and updated. Web pages are not just used to share information, but can be used to do more things.

Local Storage upgrade

In the past, browsers had almost no storage capability. HTML5 has made significant improvements in storage, providing localStorage and sessionStorage objects for small data storage, and WebDatabase for storing a large amount of data.

Limitations of cookies and cookies

Http itself is a stateless, connectionless protocol. When a user requests an action in a browser, the server does not know what the previous action has done. Therefore, it is very troublesome to store status information such as logon or not and logged-on text. The invention of cookie satisfies the needs of most state storage. Basically, a cookie is a piece of text stored in a client (browser). We can set a cookie when the server responds to the response, or modify it through javascript at the front end. Cookies have domain restrictions. Cookies in different domains do not affect each other and cannot access each other.

You can enter document in the Google Chrome console. cookie to view all available cookies on the current webpage. You can also use this method to document. cookie = "uid = 123" to set the cookie. This statement does not overwrite the previous cookie, but is automatically added to the end of the original cookie. different key-value pairs are separated. In addition to the domain restrictions, there is also a limit on the size and quantity of our data storage, a great impact. Different browsers use different restrictions, but not many.

Web Storage from HTML5

Compared with cookies, WebStorage in HTML5 specifications is more suitable for local data storage. Web Storage is easy to use and faster and safer. It is stored in a browser and not sent to the server with HTTP requests. It can easily store large amounts of data without affecting the performance of your website.

Web Storage usage

The browser has two built-in instantiated objects, sessionStorage and localStorage.

The data stored in sessionStorage is valid only during a single page session, and sessionStorage is more similar to a global variable on the page. The localStorage data will be persisted to the client and will never expire (the cookie can set the expiration time), and its capacity will not be as limited as the cookie.

Whether it is sessionStorage or localStorage, you can use the following methods or attributes:

SetItem (key, value) getItem (key) removeItem (key) length key (n) clear ()

The difference between the two is that the life cycle of the stored data is different. As long as the data is continuously accessed in this domain, the data stored in sessionStorage will always exist. Once the page or browser is closed, all sessionStorage data will disappear (that is, sessionStorage will not store the data to the disk ).

Storage event

All modifications to the Storage object will trigger the storage event on the document. The event object has the following attributes:

Domain key oldValue newValue

For example:

Document. addEventListener ("storage", function (e) {console. log ("Storage changed. name'" + e. Key + "'");});

This event is not recommended because of compatibility issues.

Of course, it does not mean that the localStorage size can be used infinitely. Different browsers have different settings, but generally each domain will have a storage space of 5 MB, which for most applications, enough.

Cache and application Cache

HTML5 provides a unique Cache mechanism: Application Cache (Application Cache)

As the name suggests, this is a cache mechanism for applications. It is mainly used to cache server-side resource files locally, at least three of them are as follows:

Accelerating application startup-saving time for downloading files

Offline access-use the pages and file resources cached offline to continue unfinished work

Saving server resources-less requests means less server pressure.

Basic Application Cache Usage

Generally, it is enabled for single-page applications.

Manifest

It is very easy to enable application caching In the document. You only need to add a manifest attribute to the HTML Tag and specify the manifest file.

<! DOCTYPE html>

<Html manifest = "/appcache. manifest">

// The html file itself will be cached

</Html>

Appcache. manifest is actually a text file, which specifies the resources that need to be cached by the browser, as shown below:

CACHE MANIFEST

Index.html

Stylesheet.css

Images/logo.png

Scripts/main. js

When the browser loads the page for the first time, it reads the file and downloads and caches the specified resources. In the preceding example, four files are cached. Because the cache is one-time, therefore, if any of the four files is unavailable, the entire cache will fail. In addition to the four files specified in the file to be cached, the html document of the specified manifest file will also be cached.

Note that the server must set the MIME type to text/cache-manifest when returning this file. Different servers use different methods to specify the MIME type, set MIME in NodeJS-based Web Server Express as follows:

Res. type ('text/cache-manifest ')

Res. sendfile (appcache. manifest file path)

The manifest file can also specify some special cache actions. The following is an example of a complete format.

CACHE MNIFEST

# Specify the resources to be cached

/Favicon. ico

Images/logo.png

Stylesheetes/style.css

Javascripts/app. js

# Resources that must be accessed when there is a network

NETWORK:

/Api

Http://api.weibo.com

# Downgrade access

FALLBACK:

If the root directory is unavailable, read the offline.html file.

// Offline.html

# If all files in the images/directory are requested when they are unavailable, read images/offline.jpg

Images/offline.png

Any manifest file can contain three different parts: cache network and FALLBACK:

CACHE: resources that will be cached. When the browser loads the page for the first time, it downloads all the files.

NETWORK: these files are white list resources. no matter whether they are offline or not, access to these resources will bypass the cache. The resource URL can use wildcards.

FALLBACK: For inaccessible resources, use the backup resources for access. The two resources are separated by spaces. The first part indicates the path when the resources are available, and the second part indicates the cache path of the backup resources. The resource URL can use wildcards.

The preceding three parts can be combined in any order and quantity.

Cache update

The famous programmer Phil Karlton once said: "in the field of computer science, there are two major challenges: how to invalidate cache and how to name a variety of things"

There are three methods for cache invalidation:

Modify the manifest file: modifying the cached file will not automatically update the cache, but changing the manifest file will re-download the entire cache list.

Use APIs to control the cache programmatically.

The user actively clears the cached data in the browser-this is of little significance to developers. It is used to test the program by clearing the cache as needed during debugging.

Because the manifest file supports annotations, And the annotation changes can also make changes to the manifest file, which leads to the update cache. We can use this feature to automatically update the cache. Use the program to generate a random value, create a line of comment, and write it into the manifest file. The random value can be the version number, text hash value, and timestamp.

Below is a simple version Generator Based on NodeJS:

Var fs = require ('fs '),

MfPath = './public/appcache. manifest ',

MfOutputPath = './public/output. manifest'

Function gernerateVersionHash (){

// Generate a random version number using the current time

Return (+ new Date (). toString (32)

}

Fs. readFile (mfPath, function (err, data ){

If (err) throw err;

Var output = '# version =' + generateVersionHash () + '\ n' + data;

Fs. writeFile (mfOutputPath, output, function (err ){

If (err) throw err;

Console. log ('file generated successfully! Path: '+ mfOutputPath)

});})

After the path is configured, you only need to run this script to update the cache every time the application is updated. Of course, you can also monitor whether the resource file you want to save is modified to automatically generate a new version of manifest file to update the cache.

Programming Interface

A better way to update the cache is to access the offline cache interface through javascript. Window. applicationCache object defines the programming interface of application cache. For example, if you want to update the cache, you can call the applicationCache. update () method, the browser will first obtain the manifest file again. If the manifest file changes, then try to update the user's cache. However, you only need to download the files to be cached. After the download is complete, call applicationCache. swapCache () to query the current cache status.

Application cache is not difficult to use, but you must pay attention to the following two problems during use:

When you access the page, the query parameters do not work. For example, index.html? The url of page00001 can be retrieved by the backend server in the first batch. After index.html is cached, no request is sent to the server for parameter correction. Note that if you need to pass parameters in the url, you can use the hash function, use javascript to process hash content.

Manifest itself may also be cached. Setting an expiration header is a solution.

The above content is edited by Lin Yan, a detailed description of HTML5 mobile Web development practices.

Related Article

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.