SlideShare ist ein Scribd-Unternehmen logo
1 von 3
Downloaden Sie, um offline zu lesen
Articles from Jinal Desai .NET
APIs in HTML5
2012-12-29 19:12:54 Jinal Desai

Storage APIs in HTML5

Storage APIs are HTML5 answers to browser cookies limitations. These APIs allows
developers to store some basic information and values that can be user specific
and tame cookies limitations like it’s length, number of cookies per website and
many more. Typical examples of such information are saving game state, saving
navigation locations, etc. The size restriction of storing data using Storage APIs is
around 5MB. This limit is suggested by W3C, but the specs provide some room for
implementation details. So actual size depends on browser, but it does not fluctuate
that much.

Local Storage
It is basic implementation of storing data locally on user’s machine. It is a key/value
pair collection. It is window.localStorage. It allows application to run offline with some
data stored on user’s machine like user’s name and preferences.

You can use localStorage object without window. Like you can use it directly as
localStorage instead of window.localStorage. However, it is better code practice to
use window.localStorage.

To check browser is supporting window.localStorage or not you can use following
function.
function isLocalStorageAvailable() {
   try {
      return 'localStorage' in window &&
             window['localStorage']!==null;
   }
   catch(err) {
      return false;
   }
}

Storing value in localStorage is very easy with it’s setItem function.

if(isLocalStorageAvailable) {
   window.localStorage.setItem("Name","Jinal Desai");
}

To get it back use getItem function of localStorage.

if(isLocalStorageAvailable) {
   var Name = window.localStorage.getItem("Name");
}

How to clear it? To clear all the data stored in the localStorage API use clear
function.
if(isLocalStorageAvailable) {
   window.localStorage.clear();
}

To remove only particular item from localStorage you can use it’s removeItem
function.

if(isLocalStorageAvailable) {
   window.localStorage.removeItem("Name");
}

Session Storage
The window.sessionStorage stores information for a single session only. The
information is lost when the user ends the session. All the functionality is same as
window.localStorage you just need to replace sessionStorage instead of
localStorage in all above examples.

Difference between Local Storage and Session Storage
The main difference is that localStorage persists information over different tabs or
windows, even if we close the browser according to the domain’s security policy
user’s choice about quota limit.

While with sessionStorage when HTML document is created, the user agent must
see to check if document’s top level browsing context has allocated a session
storage area for that document’s origin. If it has not, a new storage area for that
document’s origin must be created. So each document object has separate object
for it’s windows sessionStorage attribute. In summary, the sessionStorage object
does not persists if we close the tab/window or it does not exists if we access the
stored value via different tab/window.

AppCache API in HTNL5
In some scenarios storing user’s information in bits and pieces is not enough. You
need to store much more data so that entire application can work offline. HTML5 has
provided caching functionality so that you can cache entire file/files. So when user is
offline browser can access cached resources.

Cached resources are local thus it loads faster, it reduces server load and also
supports browsing without internet connection. AppCache API is maintaining
manifest file(.mf) for keeping track of cached pages. To enable cache, include
manifest attribute on documents html tag.
<html manifest="http://jinaldesai.net/manifest.mf">
...
</html>

Once you include manifest attribute on html document, it will automatically cache
entire html page.

Following is example of typical manifest file. The paths of all the files caches are
relative.

//Manifest file start here.
CACHE MANIFEST //Every manifest file starts with CACHE MANIFEST

NETWORK: //Network files are never cached.
share_Prices.php

FALLBACK: //Files that wasn’t cached or wasn’t save correctly
//and need to give message to user.
message_Offline.html

CACHE: //Actual cached resource.
index.html
style.css
images/logo.png
//Manifest file ends here.

To know cache status use following code.

var applicationCache = window.applicationCache;
applicationCache.status === applicationCache.UNCACHED
applicationCache.status === applicationCache.IDLE
applicationCache.status === applicationCache.CHECKING
applicationCache.status === applicationCache.DOWNLOADING
applicationCache.status === applicationCache.UPDATEREADY
applicationCache.status === applicationCache.OBSOLETE

To update cache.
var applicationCache = window.applicationCache;
applicationCache.update(); //Update user's cache
if(applicationCache.status == window.applicationCache.UPDATEREADY) {
   applicationCache.swapCache();
   //swap updated user's cache with old stored cache
}

Events in AppCache API
applicationCache.addEventListener('cached', handleCacheEvent, false);
//first time cache
applicationCache.addEventListener('checking', handleCacheEvent, false);
//checking for update
applicationCache.addEventListener('downloading', handleCacheEvent, false);
//update is available and browser is downloading update
applicationCache.addEventListener('error', handleCacheError, false);
//404 or 410, downloading failed or manifest changed
//when download in progress
applicationCache.addEventListener('noupdate', handleCacheEvent, false);
//first download
applicationCache.addEventListener('obsolete', handleCacheEvent, false);
//4040 or 410, cache being deleted
applicationCache.addEventListener('progress', handleCacheEvent, false);
//cache being fetched
applicationCache.addEventListener('updateready', handleCacheEvent, false);
//when manifest newly downloaded

Conclusion
As browser and user experiences is eveolving, HTML5 has evolved to store
information locally at user’s machine. You can use localStorage or sessionStorage
to store name/value pairs of user/application specific values or you can cache
multipages to let your user work offline.

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Empfohlen

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

APIs in HTML5 at Jinal Desai .NET

  • 1. Articles from Jinal Desai .NET APIs in HTML5 2012-12-29 19:12:54 Jinal Desai Storage APIs in HTML5 Storage APIs are HTML5 answers to browser cookies limitations. These APIs allows developers to store some basic information and values that can be user specific and tame cookies limitations like it’s length, number of cookies per website and many more. Typical examples of such information are saving game state, saving navigation locations, etc. The size restriction of storing data using Storage APIs is around 5MB. This limit is suggested by W3C, but the specs provide some room for implementation details. So actual size depends on browser, but it does not fluctuate that much. Local Storage It is basic implementation of storing data locally on user’s machine. It is a key/value pair collection. It is window.localStorage. It allows application to run offline with some data stored on user’s machine like user’s name and preferences. You can use localStorage object without window. Like you can use it directly as localStorage instead of window.localStorage. However, it is better code practice to use window.localStorage. To check browser is supporting window.localStorage or not you can use following function. function isLocalStorageAvailable() { try { return 'localStorage' in window && window['localStorage']!==null; } catch(err) { return false; } } Storing value in localStorage is very easy with it’s setItem function. if(isLocalStorageAvailable) { window.localStorage.setItem("Name","Jinal Desai"); } To get it back use getItem function of localStorage. if(isLocalStorageAvailable) { var Name = window.localStorage.getItem("Name"); } How to clear it? To clear all the data stored in the localStorage API use clear function. if(isLocalStorageAvailable) { window.localStorage.clear(); } To remove only particular item from localStorage you can use it’s removeItem
  • 2. function. if(isLocalStorageAvailable) { window.localStorage.removeItem("Name"); } Session Storage The window.sessionStorage stores information for a single session only. The information is lost when the user ends the session. All the functionality is same as window.localStorage you just need to replace sessionStorage instead of localStorage in all above examples. Difference between Local Storage and Session Storage The main difference is that localStorage persists information over different tabs or windows, even if we close the browser according to the domain’s security policy user’s choice about quota limit. While with sessionStorage when HTML document is created, the user agent must see to check if document’s top level browsing context has allocated a session storage area for that document’s origin. If it has not, a new storage area for that document’s origin must be created. So each document object has separate object for it’s windows sessionStorage attribute. In summary, the sessionStorage object does not persists if we close the tab/window or it does not exists if we access the stored value via different tab/window. AppCache API in HTNL5 In some scenarios storing user’s information in bits and pieces is not enough. You need to store much more data so that entire application can work offline. HTML5 has provided caching functionality so that you can cache entire file/files. So when user is offline browser can access cached resources. Cached resources are local thus it loads faster, it reduces server load and also supports browsing without internet connection. AppCache API is maintaining manifest file(.mf) for keeping track of cached pages. To enable cache, include manifest attribute on documents html tag. <html manifest="http://jinaldesai.net/manifest.mf"> ... </html> Once you include manifest attribute on html document, it will automatically cache entire html page. Following is example of typical manifest file. The paths of all the files caches are relative. //Manifest file start here. CACHE MANIFEST //Every manifest file starts with CACHE MANIFEST NETWORK: //Network files are never cached. share_Prices.php FALLBACK: //Files that wasn’t cached or wasn’t save correctly //and need to give message to user. message_Offline.html CACHE: //Actual cached resource. index.html style.css images/logo.png
  • 3. //Manifest file ends here. To know cache status use following code. var applicationCache = window.applicationCache; applicationCache.status === applicationCache.UNCACHED applicationCache.status === applicationCache.IDLE applicationCache.status === applicationCache.CHECKING applicationCache.status === applicationCache.DOWNLOADING applicationCache.status === applicationCache.UPDATEREADY applicationCache.status === applicationCache.OBSOLETE To update cache. var applicationCache = window.applicationCache; applicationCache.update(); //Update user's cache if(applicationCache.status == window.applicationCache.UPDATEREADY) { applicationCache.swapCache(); //swap updated user's cache with old stored cache } Events in AppCache API applicationCache.addEventListener('cached', handleCacheEvent, false); //first time cache applicationCache.addEventListener('checking', handleCacheEvent, false); //checking for update applicationCache.addEventListener('downloading', handleCacheEvent, false); //update is available and browser is downloading update applicationCache.addEventListener('error', handleCacheError, false); //404 or 410, downloading failed or manifest changed //when download in progress applicationCache.addEventListener('noupdate', handleCacheEvent, false); //first download applicationCache.addEventListener('obsolete', handleCacheEvent, false); //4040 or 410, cache being deleted applicationCache.addEventListener('progress', handleCacheEvent, false); //cache being fetched applicationCache.addEventListener('updateready', handleCacheEvent, false); //when manifest newly downloaded Conclusion As browser and user experiences is eveolving, HTML5 has evolved to store information locally at user’s machine. You can use localStorage or sessionStorage to store name/value pairs of user/application specific values or you can cache multipages to let your user work offline.