html5 local storage

32
HTML5 LOCAL STORAGE Front-End Meetup #7 Lior Zamir HPE Software Innovation Webmaster [email protected] Using HTML5 Web LocalStorage for Improve Performance and User Experience

Upload: lior-zamir

Post on 16-Apr-2017

252 views

Category:

Software


0 download

TRANSCRIPT

Page 1: HTML5 Local Storage

HTML5 LOCAL STORAGE

Front-End Meetup #7

Lior ZamirHPE Software Innovation Webmaster

[email protected]

Using HTML5 Web LocalStorage for Improve Performance and User Experience

Page 2: HTML5 Local Storage

Agenda1. Why store data on the client?2. Methods for storing data on the client-side3. HTML5 Web Storage4. Syntax + Demo5. Use Cases6. Best Practice

Page 3: HTML5 Local Storage
Page 4: HTML5 Local Storage

Why store data on the client?

Page 5: HTML5 Local Storage

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.

Page 6: HTML5 Local Storage

What are the methods for storing data

on the client-side?

Page 7: HTML5 Local Storage

Methods For Storing DataJavaScript 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.

Page 8: HTML5 Local Storage

Methods For Storing DataCookies

• 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

Page 9: HTML5 Local Storage

HTML5 Web Storage

Page 10: HTML5 Local 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

Page 12: HTML5 Local Storage

LocalStorage vs SessionStorage

Ses sion Stor age• Per sists a stor age area for the dura tion of the page ses sion.• Use it when you need to store some data tem porar ily.

• Data is available:o As long as the browser is open, includ ing page reloads/restoreso It gets deleted the time when the tab/window who cre ated the ses sion is closed

Local Stor age• Per sists the data until the user explic itly 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

Page 13: HTML5 Local Storage

Syntax

Page 14: HTML5 Local Storage

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();

};

Page 15: HTML5 Local Storage

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"];

Page 16: HTML5 Local Storage

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 ses sion Stor age is identical (just use “ses sion Stor age” instead of “localStorage”)

Page 17: HTML5 Local Storage

Example: Native API (JSON serialize of objects) vs store.jsvar 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:

Page 18: HTML5 Local Storage

Debug

Page 19: HTML5 Local Storage

Use Cases

Page 20: HTML5 Local Storage

Use Case #1Improve Performance by Caching

Page 21: HTML5 Local Storage

Use Case #1Improve Performance by

CachingA 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.

Page 22: HTML5 Local Storage

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 #1Improve Performance by Caching

We can use localStorage to make a mobile website faster!

Page 23: HTML5 Local Storage

Use Case #2Improve User Experience

Page 24: HTML5 Local Storage

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

Page 25: HTML5 Local Storage

• If the internet gets disconnected during data transfer, the user can choose to revisit the site and resend this data.

The user disconnecte

d 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

Page 26: HTML5 Local Storage

Other Use Cases• For apps that don't have a server-side (yet/ever)• For apps that live only in the client (extensions/mobile)

Page 27: HTML5 Local Storage

Best Practice

Page 28: HTML5 Local Storage

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>

Page 29: HTML5 Local Storage

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.

Page 30: HTML5 Local Storage

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.

Page 32: HTML5 Local Storage

HTML5 is here to stay!