SlideShare uma empresa Scribd logo
1 de 32
HTML5 LOCAL STORAGE
Front-End Meetup #7
Lior Zamir
HPE Software Innovation Webmaster
LiorZ@hpe.com
Using HTML5 Web LocalStorage for
Improve Performance and User Experience
Agenda
1. Why store data on the client?
2. Methods for storing data on the client-side
3. HTML5 Web Storage
4. Syntax + Demo
5. Use Cases
6. Best Practice
Why store data on the client?
Why Store Data on the Client?
Use cases:
• You want to increase performance. You can cache data
client-side so it can be retrieved without additional server
requests.
• You want to restore the state of your interface without
forcing people to sign up (HTTP is stateless…).
• You want you make your application work off-line.
What are the methods
for storing data
on the client-side?
Methods For Storing Data
JavaScript Variables
• Pros:
 The fastest and simplest solution
 No need to serialize or de-serialize data
 Ideal for single-page applications
• Cons:
 Very fragile — linking elsewhere, refreshing/closing the tab will
wipe all data
 Global variables can be overwritten and analyzed by third-party
scripts.
Methods For Storing Data
Cookies
• Pros:
 A reliable method of retaining state between the client and server
 With expiry date - data will persist beyond page refreshes and tab closing
 Supported in all modern browsers
• Cons:
 Data is added to every HTTP request header
 Values are strings only — other data must be serialized
 Storage space is limited — 4KB per cookie
 Can be deleted or blocked
 Threat to internet privacy
HTML5 Web Storage
HTML5 Web Storage
• Pros:
 Easy to use with simple name/value pairs
 Session and persistent storage options are available
 An event model is available to keep other tabs and windows synchronized
 Wide support on desktop and mobile browsers including IE8+
 Do not need to be transmitted with each HTTP request and response until
required
• Cons:
 String values only — serialization may be necessary
 Unstructured data with no transactions, indexing or searching facilities
Can I use it?
LocalStorage vs SessionStorage
SessionStorage
• Persists a storage area for the duration of the page session.
• Use it when you need to store some data temporarily.
• Data is available:
o As long as the browser is open, including page reloads/restores
o It gets deleted the time when the tab/window who created the session is closed
LocalStorage
• Persists the data until the user explicitly deletes the data.
• Use it when you need to store some data for the long term.
• Data is available:
o Even after the browser is closed and reopened
Syntax
Web Storage (Second Edition)
W3C Recommendation 19 April 2016
https://www.w3.org/TR/webstorage
interface Storage {
readonly attribute unsigned long length;
DOMString? key(unsigned long index);
getter DOMString? getItem(DOMString key);
setter void setItem(DOMString key, DOMString value);
deleter void removeItem(DOMString key);
void clear();
};
Syntax
• Options for storing data:
o localStorage.setItem("name", "value");
o localStorage.name = "value";
o localStorage["name"] = "value";
• Options for retrieving stored data:
o localStorage.getItem("name");
o localStorage.name;
o localStorage["name"];
Syntax
• Options for deleting stored data:
• localStorage.removeItem("name");
• delete localStorage.name;
• delete localStorage["name"];
• All of the stored data can be deleted from localStorage by using:
• localStorage.clear();
 The syntax of sessionStorage is identical (just use “sessionStorage” instead of “localStorage”)
Example:
Native API (JSON serialize of objects)
vs
store.js
var car = {};
car.wheels = 4;
car.engine = 1.8;
car.name = 'Alfa Romeo';
store.set('car', car);
car = store.get('car');
console.log(car);
localStorage.setItem('car', JSON.stringify(car));
car = JSON.parse(localStorage.getItem('car'));
console.log(car);
With native API + JSON serialize: With store.js:
Debug
Use Cases
Use Case #1
Improve Performance by Caching
Use Case #1
Improve Performance by Caching
A faster site and an offline site:
• Cache API and AJAX results
• Cache resources (e.g. JS/CSS files)
• basket.js - small JavaScript library supporting localStorage caching of scripts.
• Google Search and Bing make extensive use of localStorage for stashing SCRIPT
and STYLE blocks that are used on subsequent page views.
• They have shown that there are performance benefits to caching assets in
localStorage (especially on mobile) when compared to simply reading and writing
from the standard browser cache.
We can load some critical path
resources such as a JavaScript that's
required for our UX up to 3 - 5x
faster using localStorage than from
the browser's native cache.
Use Case #1
Improve Performance by Caching
We can use localStorage to make
a mobile website faster!
Use Case #2
Improve User Experience
Use Case #2
Improve user experience
• For apps that don't want to force user login for interactivity
• Save user profile and favorites (without login)
• Persistent app state:
• Open tabs, expanded/collapsed sections, layout options, dismissed
messages, etc.
• Filled-in forms -
• Login username/email
• Unsaved/unposted drafts
• Stuff that's often the same
• autoStorage.js
• If the internet gets disconnected during data transfer, the user can
choose to revisit the site and resend this data.
The user
disconnected
during data
transfer
Upon the user’s
subsequent revisit to the
site, the application
verifies if any key for the
results exists for this
domain
The site presents
the user with an
option to resend
the data (via a
button click)
Use Case #2
Improve user experience
Other Use Cases
• For apps that don't have a server-side (yet/ever)
• For apps that live only in the client (extensions/mobile)
Best Practice
Best practice
• Don't: block the UI
<head>
<script>
$('#name').html(localStorage.getItem('name'));
</script>
</head>
• Do: defer using localStorage until onload
<html>
<body></body>
<script>
window.onload = function() {
$('#name').html(localStorage.getItem('name'));
};
</script>
</html>
Best practice
• Don't: assume localStorage works or will always work.
• Do: check for feature support, check if its read/write, and check if its over quota.
Bad:
localStorage.setItem('bla', 'bla');
Better:
if (window.localStorage) {
localStorage.setItem('bla', 'bla');
}
Best:
if (window.localStorage) {
try {
localStorage.setItem('bla', 'bla');
} catch(e) {
if (e.name === 'QUOTA_EXCEEDED_ERR'
|| e.name ===
'NS_ERROR_DOM_QUOTA_REACHED') {
} else { }
} }
Most localStorage libraries take care of this for you.
The Dark Side Of
Local Storage
• Any powerful technology
comes with the danger of
people abusing it for
darker purposes.
• E.g. EverCookie, exploit
all kind of techniques,
including local storage, to
store information of a
user on their computer
even when cookies are
turned off.
Lior Zamir
LiorZ@hpe.com
https://il.linkedin.com/in/lzamir
HTML5 is here to stay!

Mais conteúdo relacionado

Mais procurados (20)

Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
XSLT
XSLTXSLT
XSLT
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Html list
Html listHtml list
Html list
 
JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Javascript
JavascriptJavascript
Javascript
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Js ppt
Js pptJs ppt
Js ppt
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Get and post methods
Get and post methodsGet and post methods
Get and post methods
 
Ajax
AjaxAjax
Ajax
 
Web Development using HTML & CSS
Web Development using HTML & CSSWeb Development using HTML & CSS
Web Development using HTML & CSS
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
 

Destaque

Local Storage for Web Applications
Local Storage for Web ApplicationsLocal Storage for Web Applications
Local Storage for Web ApplicationsMarkku Laine
 
HTML5 Storage/Cache
HTML5 Storage/CacheHTML5 Storage/Cache
HTML5 Storage/CacheAndy Wang
 
Html5 storage and browser storage
Html5 storage and browser storageHtml5 storage and browser storage
Html5 storage and browser storageSway Deng
 
Basics of html5, data_storage, css3
Basics of html5, data_storage, css3Basics of html5, data_storage, css3
Basics of html5, data_storage, css3Sreejith Nair
 
Rethinking the agile enterprise
Rethinking the agile enterpriseRethinking the agile enterprise
Rethinking the agile enterpriseBrandon Byars
 
Quality, Courtesy and a big Parking
Quality, Courtesy and a big ParkingQuality, Courtesy and a big Parking
Quality, Courtesy and a big ParkingFrancesco Fullone
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Web Storage & Web Workers
Web Storage & Web WorkersWeb Storage & Web Workers
Web Storage & Web WorkersInbal Geffen
 
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0Cory Forsyth
 
Best Web-based Data Visualization tools
Best Web-based Data Visualization tools Best Web-based Data Visualization tools
Best Web-based Data Visualization tools Atchai
 
An Overview of HTML5 Storage
An Overview of HTML5 StorageAn Overview of HTML5 Storage
An Overview of HTML5 StoragePaul Irish
 
Personas: Understanding the User Behind the Visit
Personas: Understanding the User Behind the VisitPersonas: Understanding the User Behind the Visit
Personas: Understanding the User Behind the VisitMichael King
 
Advanced Caching Concepts @ Velocity NY 2015
Advanced Caching Concepts @ Velocity NY 2015Advanced Caching Concepts @ Velocity NY 2015
Advanced Caching Concepts @ Velocity NY 2015Rakesh Chaudhary
 
HTTP/2 standard for video streaming
HTTP/2 standard for video streamingHTTP/2 standard for video streaming
HTTP/2 standard for video streamingHung Thai Le
 

Destaque (18)

Local Storage for Web Applications
Local Storage for Web ApplicationsLocal Storage for Web Applications
Local Storage for Web Applications
 
HTML5 Storage/Cache
HTML5 Storage/CacheHTML5 Storage/Cache
HTML5 Storage/Cache
 
Html5 storage and browser storage
Html5 storage and browser storageHtml5 storage and browser storage
Html5 storage and browser storage
 
Basics of html5, data_storage, css3
Basics of html5, data_storage, css3Basics of html5, data_storage, css3
Basics of html5, data_storage, css3
 
HTML 5
HTML 5HTML 5
HTML 5
 
Rethinking the agile enterprise
Rethinking the agile enterpriseRethinking the agile enterprise
Rethinking the agile enterprise
 
HTML5
HTML5HTML5
HTML5
 
Quality, Courtesy and a big Parking
Quality, Courtesy and a big ParkingQuality, Courtesy and a big Parking
Quality, Courtesy and a big Parking
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Web Storage & Web Workers
Web Storage & Web WorkersWeb Storage & Web Workers
Web Storage & Web Workers
 
Dtd
DtdDtd
Dtd
 
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
 
Best Web-based Data Visualization tools
Best Web-based Data Visualization tools Best Web-based Data Visualization tools
Best Web-based Data Visualization tools
 
An Overview of HTML5 Storage
An Overview of HTML5 StorageAn Overview of HTML5 Storage
An Overview of HTML5 Storage
 
Xml dtd
Xml dtdXml dtd
Xml dtd
 
Personas: Understanding the User Behind the Visit
Personas: Understanding the User Behind the VisitPersonas: Understanding the User Behind the Visit
Personas: Understanding the User Behind the Visit
 
Advanced Caching Concepts @ Velocity NY 2015
Advanced Caching Concepts @ Velocity NY 2015Advanced Caching Concepts @ Velocity NY 2015
Advanced Caching Concepts @ Velocity NY 2015
 
HTTP/2 standard for video streaming
HTTP/2 standard for video streamingHTTP/2 standard for video streaming
HTTP/2 standard for video streaming
 

Semelhante a HTML5 Local Storage

HTML5 and Search Engine Optimization (SEO)
HTML5 and Search Engine Optimization (SEO)HTML5 and Search Engine Optimization (SEO)
HTML5 and Search Engine Optimization (SEO)Performics.Convonix
 
Building Faster Websites
Building Faster WebsitesBuilding Faster Websites
Building Faster WebsitesCraig Walker
 
Internet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian ThilmanyInternet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian ThilmanyChristian Thilmany
 
C# cookieless session id and application state
C# cookieless session id and application stateC# cookieless session id and application state
C# cookieless session id and application stateMalav Patel
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and TricksMaksym Bruner
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3ConfEdy Dawson
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Jeremy Likness
 
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
AD113  Speed Up Your Applications w/ Nginx and PageSpeedAD113  Speed Up Your Applications w/ Nginx and PageSpeed
AD113 Speed Up Your Applications w/ Nginx and PageSpeededm00se
 
Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Web Directions
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3Neeraj Mathur
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data StorageAllan Huang
 

Semelhante a HTML5 Local Storage (20)

Web storage
Web storage Web storage
Web storage
 
HTML5 Web storage
HTML5 Web storageHTML5 Web storage
HTML5 Web storage
 
HTML5 and Search Engine Optimization (SEO)
HTML5 and Search Engine Optimization (SEO)HTML5 and Search Engine Optimization (SEO)
HTML5 and Search Engine Optimization (SEO)
 
Building Faster Websites
Building Faster WebsitesBuilding Faster Websites
Building Faster Websites
 
Internet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian ThilmanyInternet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian Thilmany
 
T5 Oli Aro
T5 Oli AroT5 Oli Aro
T5 Oli Aro
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
C# cookieless session id and application state
C# cookieless session id and application stateC# cookieless session id and application state
C# cookieless session id and application state
 
State management in ASP.net
State  management in ASP.netState  management in ASP.net
State management in ASP.net
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and Tricks
 
State management in ASP .NET
State  management in ASP .NETState  management in ASP .NET
State management in ASP .NET
 
Mini-Training: To cache or not to cache
Mini-Training: To cache or not to cacheMini-Training: To cache or not to cache
Mini-Training: To cache or not to cache
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3Conf
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
 
Html5 web storage
Html5 web storageHtml5 web storage
Html5 web storage
 
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
AD113  Speed Up Your Applications w/ Nginx and PageSpeedAD113  Speed Up Your Applications w/ Nginx and PageSpeed
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
 
Where to save my data, for devs!
Where to save my data, for devs!Where to save my data, for devs!
Where to save my data, for devs!
 
Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
 
HTML5 Data Storage
HTML5 Data StorageHTML5 Data Storage
HTML5 Data Storage
 

Mais de Lior Zamir

New CSS ways to control layout
New CSS ways to control layoutNew CSS ways to control layout
New CSS ways to control layoutLior Zamir
 
SharePoint Online (365) vs SharePoint On-Premises
SharePoint Online (365) vs SharePoint On-PremisesSharePoint Online (365) vs SharePoint On-Premises
SharePoint Online (365) vs SharePoint On-PremisesLior Zamir
 
שילוב אלמנטים גרפיים באתר אינטרנט
שילוב אלמנטים גרפיים באתר אינטרנטשילוב אלמנטים גרפיים באתר אינטרנט
שילוב אלמנטים גרפיים באתר אינטרנטLior Zamir
 
Office 2010 IT
Office 2010 ITOffice 2010 IT
Office 2010 ITLior Zamir
 
Office2007 full with_products
Office2007 full with_productsOffice2007 full with_products
Office2007 full with_productsLior Zamir
 
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבתAdo.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבתLior Zamir
 
Internet introduction
Internet introductionInternet introduction
Internet introductionLior Zamir
 
Web Technologies
Web TechnologiesWeb Technologies
Web TechnologiesLior Zamir
 
Microsoft .Net Framework
Microsoft .Net FrameworkMicrosoft .Net Framework
Microsoft .Net FrameworkLior Zamir
 
Computer Communication
Computer CommunicationComputer Communication
Computer CommunicationLior Zamir
 
Search Engines
Search EnginesSearch Engines
Search EnginesLior Zamir
 

Mais de Lior Zamir (14)

New CSS ways to control layout
New CSS ways to control layoutNew CSS ways to control layout
New CSS ways to control layout
 
SharePoint Online (365) vs SharePoint On-Premises
SharePoint Online (365) vs SharePoint On-PremisesSharePoint Online (365) vs SharePoint On-Premises
SharePoint Online (365) vs SharePoint On-Premises
 
שילוב אלמנטים גרפיים באתר אינטרנט
שילוב אלמנטים גרפיים באתר אינטרנטשילוב אלמנטים גרפיים באתר אינטרנט
שילוב אלמנטים גרפיים באתר אינטרנט
 
Office 2010 IT
Office 2010 ITOffice 2010 IT
Office 2010 IT
 
WPF
WPFWPF
WPF
 
Office2007 full with_products
Office2007 full with_productsOffice2007 full with_products
Office2007 full with_products
 
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבתAdo.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבת
 
Internet introduction
Internet introductionInternet introduction
Internet introduction
 
Web Technologies
Web TechnologiesWeb Technologies
Web Technologies
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
 
Microsoft .Net Framework
Microsoft .Net FrameworkMicrosoft .Net Framework
Microsoft .Net Framework
 
Computer Communication
Computer CommunicationComputer Communication
Computer Communication
 
Search Engines
Search EnginesSearch Engines
Search Engines
 
Web Services
Web ServicesWeb Services
Web Services
 

Último

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Último (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

HTML5 Local Storage

  • 1. HTML5 LOCAL STORAGE Front-End Meetup #7 Lior Zamir HPE Software Innovation Webmaster LiorZ@hpe.com Using HTML5 Web LocalStorage for Improve Performance and User Experience
  • 2. Agenda 1. Why store data on the client? 2. Methods for storing data on the client-side 3. HTML5 Web Storage 4. Syntax + Demo 5. Use Cases 6. Best Practice
  • 3.
  • 4. Why store data on the client?
  • 5. Why Store Data on the Client? Use cases: • You want to increase performance. You can cache data client-side so it can be retrieved without additional server requests. • You want to restore the state of your interface without forcing people to sign up (HTTP is stateless…). • You want you make your application work off-line.
  • 6. What are the methods for storing data on the client-side?
  • 7. Methods For Storing Data JavaScript Variables • Pros:  The fastest and simplest solution  No need to serialize or de-serialize data  Ideal for single-page applications • Cons:  Very fragile — linking elsewhere, refreshing/closing the tab will wipe all data  Global variables can be overwritten and analyzed by third-party scripts.
  • 8. Methods For Storing Data Cookies • Pros:  A reliable method of retaining state between the client and server  With expiry date - data will persist beyond page refreshes and tab closing  Supported in all modern browsers • Cons:  Data is added to every HTTP request header  Values are strings only — other data must be serialized  Storage space is limited — 4KB per cookie  Can be deleted or blocked  Threat to internet privacy
  • 10. HTML5 Web Storage • Pros:  Easy to use with simple name/value pairs  Session and persistent storage options are available  An event model is available to keep other tabs and windows synchronized  Wide support on desktop and mobile browsers including IE8+  Do not need to be transmitted with each HTTP request and response until required • Cons:  String values only — serialization may be necessary  Unstructured data with no transactions, indexing or searching facilities
  • 11. Can I use it?
  • 12. LocalStorage vs SessionStorage SessionStorage • Persists a storage area for the duration of the page session. • Use it when you need to store some data temporarily. • Data is available: o As long as the browser is open, including page reloads/restores o It gets deleted the time when the tab/window who created the session is closed LocalStorage • Persists the data until the user explicitly deletes the data. • Use it when you need to store some data for the long term. • Data is available: o Even after the browser is closed and reopened
  • 14. Web Storage (Second Edition) W3C Recommendation 19 April 2016 https://www.w3.org/TR/webstorage interface Storage { readonly attribute unsigned long length; DOMString? key(unsigned long index); getter DOMString? getItem(DOMString key); setter void setItem(DOMString key, DOMString value); deleter void removeItem(DOMString key); void clear(); };
  • 15. Syntax • Options for storing data: o localStorage.setItem("name", "value"); o localStorage.name = "value"; o localStorage["name"] = "value"; • Options for retrieving stored data: o localStorage.getItem("name"); o localStorage.name; o localStorage["name"];
  • 16. Syntax • Options for deleting stored data: • localStorage.removeItem("name"); • delete localStorage.name; • delete localStorage["name"]; • All of the stored data can be deleted from localStorage by using: • localStorage.clear();  The syntax of sessionStorage is identical (just use “sessionStorage” instead of “localStorage”)
  • 17. Example: Native API (JSON serialize of objects) vs store.js var car = {}; car.wheels = 4; car.engine = 1.8; car.name = 'Alfa Romeo'; store.set('car', car); car = store.get('car'); console.log(car); localStorage.setItem('car', JSON.stringify(car)); car = JSON.parse(localStorage.getItem('car')); console.log(car); With native API + JSON serialize: With store.js:
  • 18. Debug
  • 20. Use Case #1 Improve Performance by Caching
  • 21. Use Case #1 Improve Performance by Caching A faster site and an offline site: • Cache API and AJAX results • Cache resources (e.g. JS/CSS files) • basket.js - small JavaScript library supporting localStorage caching of scripts. • Google Search and Bing make extensive use of localStorage for stashing SCRIPT and STYLE blocks that are used on subsequent page views. • They have shown that there are performance benefits to caching assets in localStorage (especially on mobile) when compared to simply reading and writing from the standard browser cache.
  • 22. We can load some critical path resources such as a JavaScript that's required for our UX up to 3 - 5x faster using localStorage than from the browser's native cache. Use Case #1 Improve Performance by Caching We can use localStorage to make a mobile website faster!
  • 23. Use Case #2 Improve User Experience
  • 24. Use Case #2 Improve user experience • For apps that don't want to force user login for interactivity • Save user profile and favorites (without login) • Persistent app state: • Open tabs, expanded/collapsed sections, layout options, dismissed messages, etc. • Filled-in forms - • Login username/email • Unsaved/unposted drafts • Stuff that's often the same • autoStorage.js
  • 25. • If the internet gets disconnected during data transfer, the user can choose to revisit the site and resend this data. The user disconnected during data transfer Upon the user’s subsequent revisit to the site, the application verifies if any key for the results exists for this domain The site presents the user with an option to resend the data (via a button click) Use Case #2 Improve user experience
  • 26. Other Use Cases • For apps that don't have a server-side (yet/ever) • For apps that live only in the client (extensions/mobile)
  • 28. Best practice • Don't: block the UI <head> <script> $('#name').html(localStorage.getItem('name')); </script> </head> • Do: defer using localStorage until onload <html> <body></body> <script> window.onload = function() { $('#name').html(localStorage.getItem('name')); }; </script> </html>
  • 29. Best practice • Don't: assume localStorage works or will always work. • Do: check for feature support, check if its read/write, and check if its over quota. Bad: localStorage.setItem('bla', 'bla'); Better: if (window.localStorage) { localStorage.setItem('bla', 'bla'); } Best: if (window.localStorage) { try { localStorage.setItem('bla', 'bla'); } catch(e) { if (e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { } else { } } } Most localStorage libraries take care of this for you.
  • 30. The Dark Side Of Local Storage • Any powerful technology comes with the danger of people abusing it for darker purposes. • E.g. EverCookie, exploit all kind of techniques, including local storage, to store information of a user on their computer even when cookies are turned off.
  • 32. HTML5 is here to stay!

Notas do Editor

  1. https://en.wikipedia.org/wiki/HTML5
  2. + You have a significant quantity of client-side-only data, e.g. HTML strings or widget configuration settings.
  3. Cookie data is added to every HTTP request header. This can end up having a measurable impact on response time, especially during XHRs. Values are strings only — other data must be serialized Cookie storage space is limited —20 cookies per domain of 4KB each Cookies can be deleted or blocked Cookies were unfairly labeled as a threat to internet privacy; you may need to comply with bizarre regional rules and regulations.
  4. May exhibit poor performance on large datasets
  5. http://caniuse.com/#feat=namevalue-storage
  6. IndexedDB is at present significantly slower than localStorage for reading and writing assets. http://www.stevesouders.com/blog/2011/03/28/storager-case-study-bing-google/ basket.js - If script(s) have previously been saved locally, they will simply be loaded and injected into the current document. (If not, they will be XHR'd in for use right away, but cached so that no additional loads are required in the future).