国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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 }]);
// 對(duì)象

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 }]);
// 對(duì)象
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'中存儲(chǔ)'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:

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

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

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

// 循環(huán)遍歷所有存儲(chǔ)的值
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í)間的問候語(yǔ)
lscache.set('greeting', 'Hello World!', 2);

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

// 刪除問候語(yǔ)
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);

// 從對(duì)象中檢索數(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 }]);
// 對(duì)象

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'中存儲(chǔ)'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
// 存儲(chǔ)對(duì)象字面量;在后臺(tái)使用JSON.stringify
store.set('website', {
  name: 'SitePoint',
  loves: 'CSS'
});

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

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

// 循環(huán)遍歷所有存儲(chǔ)的值
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í)間的問候語(yǔ)
lscache.set('greeting', 'Hello World!', 2);

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

// 刪除問候語(yǔ)
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)

Which Comment Symbols to Use in JavaScript: A Clear Explanation Which Comment Symbols to Use in JavaScript: A Clear Explanation Jun 12, 2025 am 10:27 AM

In JavaScript, choosing a single-line comment (//) or a multi-line comment (//) depends on the purpose and project requirements of the comment: 1. Use single-line comments for quick and inline interpretation; 2. Use multi-line comments for detailed documentation; 3. Maintain the consistency of the comment style; 4. Avoid over-annotation; 5. Ensure that the comments are updated synchronously with the code. Choosing the right annotation style can help improve the readability and maintainability of your code.

The Ultimate Guide to JavaScript Comments: Enhance Code Clarity The Ultimate Guide to JavaScript Comments: Enhance Code Clarity Jun 11, 2025 am 12:04 AM

Yes,JavaScriptcommentsarenecessaryandshouldbeusedeffectively.1)Theyguidedevelopersthroughcodelogicandintent,2)arevitalincomplexprojects,and3)shouldenhanceclaritywithoutclutteringthecode.

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

Mastering JavaScript Comments: A Comprehensive Guide Mastering JavaScript Comments: A Comprehensive Guide Jun 14, 2025 am 12:11 AM

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScript Data Types: A Deep Dive JavaScript Data Types: A Deep Dive Jun 13, 2025 am 12:10 AM

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

See all articles