


Raid on HTML5 Javascript API Extension 3—a new experience of local storage_html5 tutorial skills
Storing data on the client can solve many problems and reduce unnecessary transmission of data:
1. Can save the status of the program: the user can know where he has been working after closing the browser and opening it again.
2. Ability to cache data: There is no need to obtain data from the server every time for a lot of data that does not change.
3. Can save user preferences: This kind of data usually does not need to be stored on the server.
Previous approach
Before HTML5 local storage, if we wanted to save persistent data on the client, we had several options:
1. HTTP cookie. The disadvantages of HTTP cookies are obvious, they can only store up to 4KB of data, and each HTTP request will be transmitted back to the server in clear text (unless you use SSL).
2. IE userData. userData is a local storage solution launched by Microsoft during the browser wars of the 1990s. It uses the behavior attribute of DHTML to store local data. It allows each page to store up to 64K data and each site to store up to 640K data. The shortcomings of userData are obvious. It's not part of the web standards, so unless your application only needs to support IE, it's of little use.
3. Flash cookies. Flash cookie is actually not the same thing as HTTP cookie. Perhaps its name should be called "Flash local storage". Flash cookie allows each website to store no more than 100K of data by default. If it exceeds, Flash will automatically request an update from the user. Large storage space, with the help of Flash's ExternalInterface interface, you can easily operate Flash's local storage through Javascript. The problem with Flash is simply that it is Flash.
4. Google Gears. Gears is an open source browser plug-in released by Google in 2007, aiming to improve the compatibility of major browsers. Gears has a built-in embedded SQL database based on SQLite and provides a unified API to access the database. After obtaining users After authorization, each site can store data of any size in the SQL database. The problem with Gears is that Google itself no longer uses it.
The dazzling variety of technologies leads to browser compatibility issues. Probably the thing that everyone uses the most here is cookies.
New experience in HTML5
In response to the above problems, HTML5 provides a more ideal solution: if what you need to store is simply a key/value pair, it can be solved data, you can use Web Storage.
Compared with Cookies, Web Storage has many advantages, which can be summarized as follows:
1. Larger storage space: Each independent storage space under IE8 is 10M, and other browsers have slightly different implementations , but are much larger than Cookie.
2. The stored content will not be sent to the server: When a cookie is set, the cookie content will be sent to the server along with the request, which is a waste of bandwidth for locally stored data. The data in Web Storage only exists locally and does not interact with the server in any way.
3. More rich and easy-to-use interfaces: Web Storage provides a richer set of interfaces, making data operations easier.
4. Independent storage space: Each domain (including subdomains) has an independent storage space. Each storage space is completely independent, so there will be no data confusion.
Web Storage Classification
Web Storage actually consists of two parts: sessionStorage and localStorage.
sessionStorage is used to locally store data in a session. These data can only be accessed by pages in the same session and the data will be destroyed when the session ends. Therefore sessionStorage is not a persistent local storage, only session-level storage.
LocalStorage is used for persistent local storage. Unless the data is actively deleted, the data will never expire.
Check whether Web Storage is supported
Web Storage is supported in all major browsers, but in order to be compatible with older browsers, you still need to check whether this technology can be used.
First way: Check whether the browser supports Web Storage by checking whether the Storage object exists:
if(typeof(Storage)!=="undefined"){
// Yes! localStorage and sessionStorage support!
// Some code... ..
} else {
// Sorry! No web storage support..
}
The second way is to check the respective objects separately, for example, check whether localStorage supports :
if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
// Yes! localStorage and sessionStorage support!
// Some code.....
}
or:
if('localStorage' in window && window['localStorage'] !== null) {
// Yes! localStorage and sessionStorage support!
// Some code.....
} else {
alert('Your browser does not support HTML5 localStorage. Try upgrading.') ;
}
or
if (!!localStorage) {
// Yes! localStorage and sessionStorage support!
// Some code.....
} else {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
}
Obviously the first way is the most direct and simplest.
Usage of Web Storage
Web Storage stores key-value pairs, and the browser stores them as strings. Remember to convert them to other formats if necessary.
Except for different uses, sessionStorage and localStorage have the same member list:
key = value: store key-value pair
setItem(key, value): store key-value pair
getItem(key): get key-value pair
removeItem(key ): Remove all key-value pairs
clear(): Clear all key-value pairs
length: The number of key-value pairs
It should be emphasized here: setItem(key,value ) method can be any type in theory, but in fact the browser will call the toString method of value to obtain its string value and store it locally, so if it is a custom type, you need to define a meaningful one yourself toString method. For example, the following example is used in combination with JSON.stringify:
var person = {'name': 'rainman', 'age': 24};
localStorage.setItem("me", JSON.stringify(person));
JSON.parse(localStorage.getItem( 'me')).name; // 'rainman'
/**
* JSON.stringify, convert JSON data into string
* JSON.stringify({'name': 'fred', 'age': 24}); // '{"name":"fred ","age":24}'
* JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
* JSON.parse, reverse JSON.stringify
* JSON.parse('["a","b","c"]') // ["a","b","c" ]
*/
In addition, when adding key-value pairs, if the number added is relatively large, compare The safe way is to check whether there is an exception exceeding the limit:
try {
localStorage.setItem(itemId, values.join(';'));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert( 'Quota exceeded!');
}
}
Web Storage's method is very simple. The following example counts the number of button clicks:
< ;head>
<script> <br />function clickCounter() <br />{ <br />if(typeof(Storage)!=="undefined") <br />{ <br />if (localStorage.clickcount) <br />{ <br />localStorage.clickcount=Number(localStorage.clickcount) 1; <br />} <br />else <br />{ <br />localStorage.clickcount=1; <br />} <br />document.getElementById ("result").innerHTML="You have clicked the button " localStorage.clickcount " time(s)."; <br />} <br />else <br />{ <br />document.getElementById("result"). innerHTML="Sorry, your browser does not support web storage..."; <br />} <br />} <br /></script>
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
