Table of Contents
Key Takeaways
Available disk space
Mobile browsers:
Desktop browsers:
Native cache vs local storage
Things have changed
Who’s using local storage?
A note on Private Browsing
Conclusion
Frequently Asked Questions (FAQs) about HTML5 Local Storage
What is the maximum storage limit for HTML5 Local Storage?
How secure is HTML5 Local Storage?
How can I check if a browser supports HTML5 Local Storage?
How can I clear data from HTML5 Local Storage?
Can I store objects or arrays in HTML5 Local Storage?
What is the difference between Local Storage and Session Storage?
How can I iterate over all values in Local Storage?
Can Local Storage be shared between subdomains?
Can Local Storage data be transferred between different browsers?
How can I handle Local Storage quota exceeded errors?
Home Web Front-end JS Tutorial HTML5 Local Storage Revisited

HTML5 Local Storage Revisited

Feb 20, 2025 am 09:37 AM

HTML5 Local Storage Revisited

Key Takeaways

  • HTML5 Local Storage, a part of the Web Storage API, allows for data storage in the browser, with a capacity of 2MB to 10MB depending on the browser, protocol, port, and top-level domain. Unlike cookies, this data is not sent back to the server and persists across sessions and device restarts.
  • While Local Storage can have a performance hit due to its synchronous nature, it can be faster than native cache on mobile devices. To optimize performance, it’s recommended to limit reads and only access Local Storage after the window.onload event to avoid blocking the UI thread.
  • Not all browsers support setting items in Local Storage during private or incognito mode, and in some cases, data stored in private mode is purged after exiting. To ensure safe use of Local Storage, it’s advisable to not only test for support but also for the capacity to get and set items.

Local storage is part of the HTML5 Web Storage API and it allows you to store data in the browser. Unlike cookies, data stored using local storage isn’t sent back to the server. All data stays on the client, and you can currently store from 2MB to 10MB. This limit is tied to the specific browser, protocol (HTTP or HTTPS), port, and top level domain in use.

In this article, we’ll discuss how to use this API to improve the performance of a website. I’ll assume that you know what local storage is and the methods exposed, but if you need a refresher I suggest you read the article An Overview of the Web Storage API by Colin Ihrig.

Available disk space

Before we start the discussion of local storage, I want to give you an overview of the available disk space in major mobile and desktop browsers. The following tables are based on the article “Working with quota on mobile browsers”.

Mobile browsers:

Browser Chrome Android Browser Firefox iOS Safari Version 40 4.3 34 6-8 Space available 10MB 2MB 10MB 5MB

Desktop browsers:

Browser Chrome Opera Firefox Safari Internet Explorer Version 40 27 34 6-8 9-11 Space available 10MB 10MB 10MB 5MB 10MB

Native cache vs local storage

When using local storage, your data will stay on the client and persist across sessions and device restarts. As I mentioned in the introduction, the limit of the local storage API is tied to the specific browser (as shown in the previous tables), protocol, port, and top level domain in use. By contrast, the space available on the browser’s native cache is shared across websites, and it’s much smaller on mobile devices. It gets flushed frequently, sometimes even within the same visit. Mobile devices have an additional issue: they’re less powerful than desktop devices, so achieving good performance is a must.

There has been a lot of discussion about local storage performance. For example, Christian Heilmann, formerly with Mozilla, wrote “There is no simple solution for local storage”. Local storage can have a performance hit if not used carefully. The first thing you need to take into account is that it’s a synchronous API, therefore it blocks the main UI thread. Local storage writes and reads data from the hard drive, which can be a much more expensive operation than reading from memory. In order to give you access to the data, local storage needs to read the data from the disk, and that’s where the performance hit occurs. This performance hit is not a major issue with small amounts of data, but it can be noticeable using the full storage limit.

As a good practice you should try to perform as few reads as possible. Also, because we are dealing with a synchronous API, you should try to read data from local storage only after the window.onload event has fired, to avoid blocking the UI thread.

Things have changed

But things are getting better. An article published by Peter McLachlan of Mobify explained that local storage can be 5x faster than native cache on mobile devices.

HTML5 Local Storage Revisited

In the appendix of the same article you can see the evolution of the performance of local storage on mobile browsers and how much it’s improved. You can also see that local storage has always been faster than native cache.

Who’s using local storage?

There are some recent cases of websites using local storage to cache assets, such as The Guardian who are using local storage for critical path CSS. You can view this presentation given at Velocity conference 2014 to understand more about how they are able to do this.

Also Smashing Magazine recently started caching web fonts in local storage. In this article about some performance improvements implemented recently on their website, they report deferring web fonts and caching them in local storage among the changes that led to the most effective improvements.

A note on Private Browsing

As reported on caniuse.com, under the tab known issues, when running in private or incognito mode, Safari, iOS Safari, and Android browsers don’t support setting items in local storage.

Other browsers such as Chrome and Firefox allow you to store data in local storage under private mode, but the data is purged when you exit private mode. This is due to privacy issues, as someone might use the persistent data to learn about the user’s actions when in private mode.

This issue may break your application’s behavior if a value set under a previous session is expected to be there at a subsequent visit. So, in order to use local storage safely, it’s a good practice not only to test for support, but also to test for the capacity to get and set items.

For more info on local storage behavior under private mode and on how to check local storage content in different browsers, you can use the article “Don’t Forget To Check Private Browsing Mode When Testing” as a reference.

Conclusion

Maybe it’s time that we start revisiting local storage and its potential usage, especially on mobile devices where we can use it to avoid latency bottlenecks. We can start thinking about new ways to cache our assets, and then serve them instantly to our users. We’ve seen there are already some successful implementations of local storage usage in unconventional ways.

Frequently Asked Questions (FAQs) about HTML5 Local Storage

What is the maximum storage limit for HTML5 Local Storage?

The maximum storage limit for HTML5 Local Storage varies across different browsers. However, most modern browsers offer around 5MB of storage per domain. This is significantly larger than the 4KB (approximately 4096 bytes) offered by cookies. It’s important to note that this storage is per domain, not per individual local storage object.

How secure is HTML5 Local Storage?

HTML5 Local Storage is not designed to store sensitive data. Unlike HTTP cookies, data stored in local storage is not sent back to the server with every HTTP request. This means it’s less vulnerable to certain types of attacks, such as cross-site scripting (XSS). However, it’s still susceptible to other types of attacks, such as cross-site scripting (XSS) and cross-site request forgery (CSRF). Therefore, it’s recommended not to store sensitive information like passwords or credit card numbers in local storage.

How can I check if a browser supports HTML5 Local Storage?

You can check if a browser supports HTML5 Local Storage by using the ‘in’ operator in JavaScript. Here’s a simple code snippet that checks for local storage support:

if ('localStorage' in window && window['localStorage'] !== null) {
// Local storage is supported
} else {
// Local storage is not supported
}

How can I clear data from HTML5 Local Storage?

You can clear data from HTML5 Local Storage using the clear() method. This method removes all key-value pairs from the local storage for the current domain. Here’s a simple code snippet:

localStorage.clear();

Can I store objects or arrays in HTML5 Local Storage?

Yes, you can store objects or arrays in HTML5 Local Storage. However, local storage only supports string key-value pairs. Therefore, you need to convert your object or array into a string using JSON.stringify() before storing it, and convert it back into an object or array using JSON.parse() when retrieving it.

What is the difference between Local Storage and Session Storage?

The main difference between Local Storage and Session Storage lies in their lifespan and scope. Data in Local Storage persists even when the browser is closed and reopened, while data in Session Storage is cleared when the page session ends, i.e., when the browser is closed.

How can I iterate over all values in Local Storage?

You can iterate over all values in Local Storage using a simple for loop in combination with the localStorage.key() method and the localStorage.getItem() method.

Can Local Storage be shared between subdomains?

No, Local Storage cannot be shared between subdomains. Each subdomain has its own separate local storage.

Can Local Storage data be transferred between different browsers?

No, Local Storage data cannot be transferred between different browsers. Each browser has its own separate local storage.

How can I handle Local Storage quota exceeded errors?

When the Local Storage quota is exceeded, a QUOTA_EXCEEDED_ERR exception is thrown. You can handle this exception by catching it in a try-catch block and taking appropriate action, such as clearing some space or notifying the user.

The above is the detailed content of HTML5 Local Storage Revisited. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles