亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Web Front-end JS Tutorial 9 JavaScript Libraries for Working with Local Storage

9 JavaScript Libraries for Working with Local Storage

Feb 19, 2025 am 08:47 AM

9 JavaScript Libraries for Working with Local Storage

HTML5 local storage API (part of web storage) has excellent browser support and is being applied in more and more applications. It has a simple API, but it also has some disadvantages similar to cookies.

I have encountered quite a few tools and libraries using the localStorage API over the past year or so, so I have sorted them out into this post with some code examples and feature discussions.

Key points

  • HTML5 local storage API is widely supported and is becoming more and more common in applications, but it also has some limitations similar to cookies. Various JavaScript libraries have been developed to improve and extend their capabilities.
  • Lockr, store.js, and lscache provide wrappers for the localStorage API, providing additional usage methods and functions. These include storing different data types without manual conversion, deeper browser support, and simulation of Memcached memory object caching system.
  • SecStore.js and localForage provide more professional features. secStore.js adds a layer of security through the Stanford Javascript Crypto Library, while localForage built by Mozilla provides an asynchronous storage API using IndexedDB or WebSQL.
  • Other libraries such as Basil.js and lz-string provide unique features. Basil.js is a unified localStorage, sessionStorage, and cookie API that allows you to define namespaces, storage method priorities, and default storage. lz-string allows storage of large amounts of data in localStorage via compression.

Lockr

Lockr is a wrapper for the localStorage API that allows you to use many useful methods and features. For example, while localStorage is limited to storing strings, Lockr allows you to store different data types without having to convert them yourself:

Lockr.set('website', 'SitePoint'); // 字符串
Lockr.set('categories', 8); // 數(shù)字
Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);
// 對象

Other functions include:

  • Use the Lockr.get() method to retrieve all key-value pairs
  • Compile all key-value pairs into an array using the Lockr.getAll() method
  • Use the Lockr.flush() method to delete all stored key-value pairs
  • Add/remove values ??under hash key using Lockr.sadd and Lockr.srem

The Local Storage Bridge

A 1KB library for using localStorage as a communication channel to facilitate message exchange between tabs in the same browser. Once the library is included, here is the sample code you can use:

// 發(fā)送消息
lsbridge.send('my-namespace', { 
  message: 'Hello world!' 
});

// 監(jiān)聽消息
lsbridge.subscribe('my-namespace', function(data) {
  console.log(data); // 打?。?Hello world!'
});

As shown, the send() method creates and sends messages, and the subscribe() method allows you to listen for specified messages. You can read more about the library in this blog post.

Barn

This library provides a Redis-like API that provides a "fast, atomized persistent storage layer" on top of localStorage. Below is a sample code snippet taken from the README of the repo. It demonstrates many methods available.

Lockr.set('website', 'SitePoint'); // 字符串
Lockr.set('categories', 8); // 數(shù)字
Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);
// 對象
Other features of the

API include the ability to use the start/end values ??to get ranges, get items arrays, and compress the entire data store to save space. This repo contains a complete reference to all methods and their functions.

store.js

This is another wrapper similar to Lockr, but this time it provides deeper browser support through fallback. README explains, "store.js uses localStorage when available and falls back to userData behavior in IE6 and IE7. There is no Flash to slow down page loading. There is no cookie to increase the burden on network requests."

The basic API is explained in the comments in the following code:

// 發(fā)送消息
lsbridge.send('my-namespace', { 
  message: 'Hello world!' 
});

// 監(jiān)聽消息
lsbridge.subscribe('my-namespace', function(data) {
  console.log(data); // 打?。?Hello world!'
});

In addition, there are some more advanced features:

var barn = new Barn(localStorage);

barn.set('key', 'val');
console.log(barn.get('key')); // val

barn.lpush('list', 'val1');
barn.lpush('list', 'val2');
console.log(barn.rpop('list')); // val1
console.log(barn.rpop('list')); // val2

barn.sadd('set', 'val1');
barn.sadd('set', 'val2');
barn.sadd('set', 'val3');
console.log(barn.smembers('set')); // ['val1', 'val2', 'val3']
barn.srem('set', 'val3');
console.log(barn.smembers('set')); // ['val1', 'val2']

README on GitHub repo details the depth of browser support and potential bugs and pitfalls to be considered (for example, some browsers do not allow local storage in privacy mode).

lscache

lscache is another localStorage wrapper, but with some extra features. You can use it as a simple localStorage API or use the functionality of emulating Memcached (memory object caching system).

lscache exposes the following method, which is described in the comments in the code:

// 在'website'中存儲'SitePoint'
store.set('website', 'SitePoint');

// 獲取'website'
store.get('website');

// 刪除'website'
store.remove('website');

// 清除所有鍵
store.clear();

Like the previous library, this library also handles serialization, so you can store and retrieve objects:

// 存儲對象字面量;在后臺使用JSON.stringify
store.set('website', {
  name: 'SitePoint',
  loves: 'CSS'
});

// 獲取存儲的對象;在后臺使用JSON.parse
var website = store.get('website');
console.log(website.name + ' loves ' + website.loves);

// 獲取所有存儲的值
console.log(store.getAll());

// 循環(huán)遍歷所有存儲的值
store.forEach(function(key, val) {
  console.log(key, val);
});

Finally, lscache allows you to divide data into "buckets". Check out this code:

// 設(shè)置一個(gè)帶有2分鐘過期時(shí)間的問候語
lscache.set('greeting', 'Hello World!', 2);

// 獲取并顯示問候語
console.log(lscache.get('greeting'));

// 刪除問候語
lscache.remove('greeting');

// 刷新整個(gè)緩存項(xiàng)目
lscache.flush();

// 只刷新過期的項(xiàng)目
lscache.flushExpired();

Note that in the second log, the result is null. This is because I set up a custom bucket before logging the result. Once I set up a bucket, nothing added to lscache before this will be inaccessible, even if I try to refresh it. Only items in the "other" bucket are accessible or refreshable. Then when I reset the bucket I was able to access my original data again.

secStore.js

secStore.js is a data storage API that adds an optional security layer through the Stanford Javascript Crypto Library. secStore.js allows you to select storage methods: localStorage, sessionStorage, or cookie. To use secStore.js you must also include the sjcl.js library mentioned earlier.

The following is an example showing how to save some data with the encrypt option set to "true":

lscache.set('website', {
  'name': 'SitePoint',
  'category': 'CSS'
}, 4);

// 從對象中檢索數(shù)據(jù)
console.log(lscache.get('website').name);
console.log(lscache.get('website').category);

Note the set() method used, which passes in the options you specified (including custom data) and a callback function that allows you to test the results. Then, we can use the get() method to retrieve the data:

lscache.set('website', 'SitePoint', 2);
console.log(lscache.get('website')); // 'SitePoint'

lscache.setBucket('other');
console.log(lscache.get('website')); // null

lscache.resetBucket();
console.log(lscache.get('website')); // 'SitePoint'

If you want to use sessionStorage or cookies instead of localStorage in secStore.js, you can define it in the options:

var storage = new secStore;
var options = {
    encrypt: true,
      data: {
        key: 'data goes here'
      }
    };

storage.set(options, function(err, results) {
  if (err) throw err;
  console.log(results);
});

localForage

This library built by Mozilla provides you with a simple localStorage-like API, but uses asynchronous storage via IndexedDB or WebSQL. The API is exactly the same as localStorage (getItem(), setItem(), etc.), except that its API is asynchronous and the syntax requires the use of callbacks.

So for example, you won't get the return value regardless of whether you set or get the value, but you can handle the data passed to the callback function and (optional) handle the error:

Lockr.set('website', 'SitePoint'); // 字符串
Lockr.set('categories', 8); // 數(shù)字
Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);
// 對象

Some other points about localForage:

  • Support JavaScript Promise
  • Like other libraries, it is not only limited to storing strings, but also setting and getting objects
  • Allows you to set database information using the config() method

Basil.js

Basil.js is described as a unified localStorage, sessionStorage, and cookie API, which contains some unique and very easy to use features. The basic method can be used as follows:

// 發(fā)送消息
lsbridge.send('my-namespace', { 
  message: 'Hello world!' 
});

// 監(jiān)聽消息
lsbridge.subscribe('my-namespace', function(data) {
  console.log(data); // 打?。?Hello world!'
});

You can also use Basil.js to test if localStorage is available:

var barn = new Barn(localStorage);

barn.set('key', 'val');
console.log(barn.get('key')); // val

barn.lpush('list', 'val1');
barn.lpush('list', 'val2');
console.log(barn.rpop('list')); // val1
console.log(barn.rpop('list')); // val2

barn.sadd('set', 'val1');
barn.sadd('set', 'val2');
barn.sadd('set', 'val3');
console.log(barn.smembers('set')); // ['val1', 'val2', 'val3']
barn.srem('set', 'val3');
console.log(barn.smembers('set')); // ['val1', 'val2']

Basil.js also allows you to use cookies or sessionStorage:

// 在'website'中存儲'SitePoint'
store.set('website', 'SitePoint');

// 獲取'website'
store.get('website');

// 刪除'website'
store.remove('website');

// 清除所有鍵
store.clear();

Finally, in the option object, you can use the option object to define the following:

  • Namespaces for different parts of the data
  • Preferential order of storage methods to be used
  • Default storage method
  • Expiration date of cookies
// 存儲對象字面量;在后臺使用JSON.stringify
store.set('website', {
  name: 'SitePoint',
  loves: 'CSS'
});

// 獲取存儲的對象;在后臺使用JSON.parse
var website = store.get('website');
console.log(website.name + ' loves ' + website.loves);

// 獲取所有存儲的值
console.log(store.getAll());

// 循環(huán)遍歷所有存儲的值
store.forEach(function(key, val) {
  console.log(key, val);
});

lz-string

lz-string utility allows you to store large amounts of data in localStorage by using compression, and it is very easy to use. After including the library on the page, you can do the following:

// 設(shè)置一個(gè)帶有2分鐘過期時(shí)間的問候語
lscache.set('greeting', 'Hello World!', 2);

// 獲取并顯示問候語
console.log(lscache.get('greeting'));

// 刪除問候語
lscache.remove('greeting');

// 刷新整個(gè)緩存項(xiàng)目
lscache.flush();

// 只刷新過期的項(xiàng)目
lscache.flushExpired();

Please pay attention to the use of compress() and decompress() methods. The comments in the above code show the length values ??before and after compression. You can see how beneficial this will be, as client storage is always limited in space.

As explained in the library documentation, you can choose to compress the data into Uint8Array (a newer data type in JavaScript) and even compress the data to store externally on the client.

Honorable Mentions

The above tools may help you do almost everything you want to do in localStorage, but if you are looking for more, here are some more related tools and libraries you might want to check out.

  • LokiJS – A fast, in-memory document-oriented data store for node.js, browsers, and Cordova.
  • AngularJS client storage – Angular JS namespace client storage. Write to localStorage and fall back to cookie. There are no external dependencies except Angular core; ngCookies are not dependent.
  • AlaSQL.js – JavaScript SQL database and Node.js for browsers. Handle traditional associated tables and nested JSON data (NoSQL). Export, store and import data from localStorage, IndexedDB, or Excel.
  • angular-locker – Simple and configurable abstraction of local/session storage in Angular projects, providing a powerful and easy-to-use smooth API.
  • jsCache – Enable cache of JavaScript files, CSS stylesheets, and images using localStorage.
  • LargeLocalStorage – Overcome various browser flaws and provide large key-value storage on the client side.

Do you know other libraries?

If you have built some tools to enhance client storage on top of the localStorage API or related tools, feel free to let us know in the comments.

(The rest of the article is FAQ, which has been rewritten and streamlined according to the original text, and the original intention is maintained)

Frequently Asked Questions about JavaScript Local Repositories (FAQ)

Q: What are the benefits of using JavaScript local repositories?

A: JavaScript local repository provides many benefits. They provide a more efficient way to store data on the client side, which can significantly improve the performance of web applications. These libraries also provide a higher level of security than traditional data storage methods, as they allow data encryption. Additionally, they provide a more user-friendly interface for data management, making it easier for developers to use local storage.

Q: How does local storage work in JavaScript?

A: Local storage in JavaScript allows web applications to persist in storing data in a web browser. Unlike cookies, local storage does not expire and is not sent back to the server, making it a more efficient method of data storage. Data stored in local storage is saved across browser sessions, meaning it is still available even if the browser is closed and reopened.

Q: Can I use local storage for sensitive data?

A: While local storage provides a convenient way to store data on the client, it is not recommended to use it for storing sensitive data. This is because local storage is not designed as a secure storage mechanism. Data stored in local storage can be easily accessed and manipulated using simple JavaScript code. Therefore, sensitive data such as passwords, credit card numbers, or personal user information should not be stored in local storage.

Q: How to manage data in local storage?

A: Managing data in local storage involves three main actions: setting up items, getting items, and deleting items. To set the project, you can use the setItem() method, which accepts two parameters: key and value. To retrieve an item, you can use the getItem() method, which accepts the key as an argument and returns the corresponding value. To delete an item, you can use the removeItem() method, which accepts a key as an argument.

Q: What are some popular local JavaScript repositories?

A: There are several popular local repositories for JavaScript, including store.js, localForage, and js-cookie. Store.js provides a simple and consistent API for local storage and runs on all major browsers. LocalForage provides a powerful asynchronous storage API and supports IndexedDB, WebSQL and localStorage. Js-cookie is a lightweight library for handling cookies that can be used as a fallback when local storage is unavailable.

Q: How to check if local storage is available?

A: You can use the simple try/catch block in JavaScript to check if local storage is available. The window.localStorage property can be used to access local storage objects. Local storage is available if this property exists and can be used to set up and retrieve items.

Q: What is the storage limit for local storage?

A: The storage limits for local storage vary from browser to browser, but are usually around 5MB. This is much larger than the storage limit of cookies (only 4KB). However, it is better to be aware of the amount of data you store in your local storage, as too much data can slow down your web applications.

Q: Can local storage be shared between different browsers?

A: No, local storage cannot be shared between different browsers. Each web browser has its own independent local storage, so the data stored in one browser will not be available in another. This is important when designing web applications that rely on local storage.

Q: How to clear all data in local storage?

A: You can use the clear() method to clear all data in the local storage. This method does not accept any parameters and will delete all items from the local storage. Be careful when using this method, as it permanently deletes all data in the local storage.

Q: Can local storage be used on mobile devices?

A: Yes, local storage can be used on mobile devices. Most modern mobile web browsers support local storage, so you can use it on desktop and mobile devices to store data. However, storage limitations on mobile devices may be low, so it is important to consider this when designing web applications.

The above is the detailed content of 9 JavaScript Libraries for Working with Local Storage. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Jul 04, 2025 am 02:42 AM

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

See all articles