[フレーム]
MW
Uploaded byMike West
KEY, PPTX2,753 views

Intro to IndexedDB (Beta)

The document provides an overview of various offline storage options in web development, including IndexedDB, Local Storage, WebSQL, and the File API. It details the features, advantages, and limitations of these storage mechanisms, with a particular focus on IndexedDB's capabilities for structured data storage and asynchronous operations. Additionally, it includes practical examples and references for implementing IndexedDB in applications.

Download as KEY, PPTX
41 / 45
// Assuming that `db` has been set somewhere in the current // scope, we use it to create a transaction: var readTransaction = db.transaction( [ "contacts" ], // The Object Stores to lock IDBTransation.READ_ONLY // Lock type (READ_ONLY, READ_WRITE) ); // Open the `contact` store... var store = readTransaction.objectStore( "contacts" ); // ... and generate a cursor to walk the complete list: var readCursor = store.openCursor(); // Setup a handler for the cursor’s `success` event: readCursor.onsuccess = function ( e ) { if ( e.result ) { // You now have access to the key via `e.result.key`, and // the stored object via `e.result.value`. For example: console.log( e.result.value.email ); // mkwst@google.com } else { // If the `success` event’s `result` is null, you’ve reached // the end of the cursor’s list. } };
IndexedDB Mike West @mikewest, mkwst@google.com SV GTUG, 2010年12月14日
A IndexedDB T ] [ B E Mike West @mikewest, mkwst@google.com
Offline
Storage Options
Cookies http://www.flickr.com/photos/ilmungo/65345233/in/photostream/
• Simple, key/value pairs, Cookies "shared" between server and client. • Excellent for maintaining state, poor for anything else, as they are unstructured, and incur a significant overhead for each HTTP request.
Local Storage http://www.flickr.com/photos/photohome_uk/1494590209/
Local Storage • The simplicity of cookies, tuned for higher-capacity, client-side-only storage. • Dead simple API: localStorage.setItem( ‘key’, ‘value’ ); localStorage.getItem( ‘key’ ); // ‘value’ • Values are unstructured strings: • Filtering and search are O(n), unless you layer some indexing on top. • Structure requires JSON.stringify & JSON.parse
WebSQL http://www.flickr.com/photos/nickperez/2569423078/
WebSQL • A real, relational database implementation on the client (SQLite) • Data can be highly structured, and JOIN enables quick, ad-hoc access • Big conceptual overhead (SQL), no finely grained locking • Not very JavaScripty, browser support is poor, and the spec has been more or less abandoned.
File API http://www.flickr.com/photos/daddo83/3406962115/
File API ?
IndexedDB http://www.flickr.com/photos/31408547@N06/4671916278/
IndexedDB • Sits somewhere between full-on SQL and unstructured key-value pairs in localStorage. • Values are stored as structured JavaScript objects, and an indexing system facilitates filtering and lookup. • Asynchronous, with moderately granular locking • Joining normalized data is a completely manual process.
IndexedDB Concepts
Practically everything is asynchronous. Callbacks are your friends.
Databases are named, and contain one or more named Object Stores
contacts
Object Stores define a property which every stored object must contain, explicitly or implicitly.
contacts 1 2 3 4 5 6 7 8 9
Values in an Object Store are structured, but don’t have a rigidly defined schema.
contacts 1 2 3 4 5 6 7 8 9
Object Stores can contain one or more Indexes that make filtering and lookup possible via arbitrary properties.
contacts 1 2 3 4 5 6 7 8 9
IndexedDB API
T A ] [ B E IndexedDB API
Vendor prefixes: webkitIndexedDB & moz_indexedDB
// Deal with vendor prefixes if ( "webkitIndexedDB" in window ) { window.indexedDB = window.webkitIndexedDB; window.IDBTransaction = window.webkitIDBTransaction; window.IDBKeyRange = window.webkitIDBKeyRange; // ... } else if ( "moz_indexedDB" in window ) { window.indexedDB = window.moz_indexedDB; } if ( !window.indexedDB ) { // Browser doesn’t support indexedDB, do something // clever, and then exit early. }
Database creation is asynchronous
var dbRequest = window.indexedDB.open( "AddressBook", // Database ID "All my friends ever" // Database Description ); // The result of `open` is _not_ the database. // It’s a reference to the request to open // the database. Listen for its `success` and // `error` events, and respond appropriately. dbRequest.onsuccess = function ( e ) { ... }; dbRequest.onerror = function ( e ) { ... };
Databases are versioned...
// The `result` attribute of the `success` event // holds the communication channel to the database dbRequest.onsuccess = function ( e ) { var db = e.result; // Bootstrapping: if the user is hitting the page // for the first time, she won’t have a database. // We can detect this by inspecting the database’s // `version` attribute: if ( db.version === "" ) { // Empty string means the database hasn’t been versioned. // Set up the database by creating any necessary // Object Stores, and populating them with data // for the first run experience. } else if ( db.version === "1.0" ) { // 1.0 is old! Let’s make changes! } else if ( db.version === "1.1" ) { // We’re good to go! } // ... };
... and versioning is asynchronous.
dbRequest.onsuccess = function ( e ) { var db = e.result; if ( db.version === "" ) { // We’re dealing with an unversioned DB. Versioning is, of // course, asynchronous: var versionRequest = db.setVersion( "1.0" ); versionRequest.onsuccess = function ( e ) { // Here’s where we’ll set up the Object Stores // and Indexes. }; } // ... };
Creating Object Stores and Indexes
dbRequest.onsuccess = function ( e ) { var db = e.result; if ( db.version === "" ) { var versionRequest = db.setVersion( "1.0" ); // Setting a version creates an implicit Transaction, meaning // that either _everything_ in the callback succeeds, or // _everything_ in the callback fails. versionRequest.onsuccess = function ( e ) { // Object Store creation is atomic, but can only take // place inside version-changing transaction. var store = db.createObjectStore( "contacts", // The Object Store’s name "id", // The name of the property to use as a key true // Is the key auto-incrementing? ); // ... }; } // ... };
dbRequest.onsuccess = function ( e ) { var db = e.result; if ( db.version === "" ) { var versionRequest = db.setVersion( "1.0" ); versionRequest.onsuccess = function ( e ) { var store = db.createObjectStore( "contacts", "id", true ); store.createIndex( "CellPhone", // The index’s name "cell", // The property to be indexed false // Is this index a unique constraint? ); }; } // ... };
Writing Data (is asynchronous)
// Assuming that `db` has been set somewhere in the current // scope, we use it to create a transaction: var writeTransaction = db.transaction( [ "contacts" ], // The Object Stores to lock IDBTransation.READ_WRITE // Lock type (READ_ONLY, READ_WRITE) ); // Open a contact store... var store = writeTransaction.objectStore( "contacts" ); // ... and generate a write request: var writeRequest = store.add( { "name": "Mike West", "email": "mkwst@google.com" } ); writeRequest.onerror = function ( e ) { writeTransaction.abort(); }; // Transactions are "complete" (not "committed"?) either when // they fall out of scope, or when all activities in the // transaction have finished (whichever happens last) writeTransaction.oncomplete = function ( e ) { ... };
Reading Data (is asynchronous)
// Assuming that `db` has been set somewhere in the current // scope, we use it to create a transaction: var readTransaction = db.transaction( [ "contacts" ], // The Object Stores to lock IDBTransation.READ_ONLY // Lock type (READ_ONLY, READ_WRITE) ); // Open the `contact` store... var store = readTransaction.objectStore( "contacts" ); // ... and generate a cursor to walk the complete list: var readCursor = store.openCursor(); // Setup a handler for the cursor’s `success` event: readCursor.onsuccess = function ( e ) { if ( e.result ) { // You now have access to the key via `e.result.key`, and // the stored object via `e.result.value`. For example: console.log( e.result.value.email ); // mkwst@google.com } else { // If the `success` event’s `result` is null, you’ve reached // the end of the cursor’s list. } };
Querying (is asynchronous)
var t = db.transaction( [ "contacts" ], IDBTransation.READ_ONLY ); var s = t.objectStore( "contacts" ); // ... and generate a cursor to walk a bounded list, for example // only those names between M and P (inclusive) var bounds = new IDBKeyRange.bound( "M", // Lower bound "Q", // Upper bound true, // Include lower bound? false // Include upper bound? ); var readCursor = store.openCursor( bounds ); // Setup a handler for the cursor’s `success` event: readCursor.onsuccess = function ( e ) { // process `e.result` };
Further Reading The IndexedDB Spec: http://www.w3.org/TR/IndexedDB/ "Firefox 4: An Early Walkthrough of IndexedDB": http://hacks.mozilla.org/2010/06/comparing- indexeddb-and-webdatabase/ Mozilla Developer Docs: https://developer.mozilla.org/en/IndexedDB
Questions? Mike West @mikewest mkwst@google.com http://mikewest.org/

More Related Content

Powerful persistence layer with Google Guice & MyBatis
PDF
Powerful persistence layer with Google Guice & MyBatis
MongoDB & NoSQL 101
PDF
MongoDB & NoSQL 101
Doctrine and NoSQL
PDF
Doctrine and NoSQL
Doctrine for NoSQL
PDF
Doctrine for NoSQL
JavaScript & Dom Manipulation
PPT
JavaScript & Dom Manipulation
Configuration Entities in Drupal 8
PDF
Configuration Entities in Drupal 8
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
PPTX
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Mastering Oracle ADF Bindings
PDF
Mastering Oracle ADF Bindings
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
MongoDB & NoSQL 101
MongoDB & NoSQL 101
Doctrine and NoSQL
Doctrine and NoSQL
Doctrine for NoSQL
Doctrine for NoSQL
JavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Configuration Entities in Drupal 8
Configuration Entities in Drupal 8
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Mastering Oracle ADF Bindings
Mastering Oracle ADF Bindings

What's hot

JavaScript JQUERY AJAX
PPT
JavaScript JQUERY AJAX
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
PDF
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
Knockout.js
PPTX
Knockout.js
Java script
PPTX
Java script
Handlebars.js
PDF
Handlebars.js
Simpler Core Data with RubyMotion
PDF
Simpler Core Data with RubyMotion
Persistent Memoization with HTML5 indexedDB and jQuery Promises
PDF
Persistent Memoization with HTML5 indexedDB and jQuery Promises
Lecture 5: Client Side Programming 1
PPTX
Lecture 5: Client Side Programming 1
Angular JS2 Training Session #1
PDF
Angular JS2 Training Session #1
Consume Spring Data Rest with Angularjs
ODP
Consume Spring Data Rest with Angularjs
Simplify AJAX using jQuery
PDF
Simplify AJAX using jQuery
RESTfull with RestKit
KEY
RESTfull with RestKit
JS basics
PPTX
JS basics
Intorduction of Playframework
PPT
Intorduction of Playframework
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
PDF
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
jQuery -Chapter 2 - Selectors and Events
PDF
jQuery -Chapter 2 - Selectors and Events
Lecture 6: Client Side Programming 2
PPTX
Lecture 6: Client Side Programming 2
Web components
PPTX
Web components
Modular javascript
PPTX
Modular javascript
Web internship Yii Framework
PDF
Web internship Yii Framework
JavaScript JQUERY AJAX
JavaScript JQUERY AJAX
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
Knockout.js
Knockout.js
Java script
Java script
Handlebars.js
Handlebars.js
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
Persistent Memoization with HTML5 indexedDB and jQuery Promises
Persistent Memoization with HTML5 indexedDB and jQuery Promises
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
Angular JS2 Training Session #1
Angular JS2 Training Session #1
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with Angularjs
Simplify AJAX using jQuery
Simplify AJAX using jQuery
RESTfull with RestKit
RESTfull with RestKit
JS basics
JS basics
Intorduction of Playframework
Intorduction of Playframework
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
Web components
Web components
Modular javascript
Modular javascript
Web internship Yii Framework
Web internship Yii Framework

Viewers also liked

Magnolia & Angular JS - an Approach for Javascript RIAs Delivered by a CMS
PDF
Magnolia & Angular JS - an Approach for Javascript RIAs Delivered by a CMS
How Angular2 Can Improve Your AngularJS Apps Today!
PDF
How Angular2 Can Improve Your AngularJS Apps Today!
Angular2 + New Firebase in Action
PPTX
Angular2 + New Firebase in Action
Angular2 + Ng-Lightning + Lightning Design System = Great Apps
PPTX
Angular2 + Ng-Lightning + Lightning Design System = Great Apps
Angular2 workshop
PDF
Angular2 workshop
29 Essential AngularJS Interview Questions
PDF
29 Essential AngularJS Interview Questions
Getting Started with Angular 2
PDF
Getting Started with Angular 2
byFITC
Nativescript with angular 2
PPTX
Nativescript with angular 2
Building Universal Applications with Angular 2
PDF
Building Universal Applications with Angular 2
Advanced AngularJS Concepts
PDF
Advanced AngularJS Concepts
Magnolia & Angular JS - an Approach for Javascript RIAs Delivered by a CMS
Magnolia & Angular JS - an Approach for Javascript RIAs Delivered by a CMS
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!
Angular2 + New Firebase in Action
Angular2 + New Firebase in Action
Angular2 + Ng-Lightning + Lightning Design System = Great Apps
Angular2 + Ng-Lightning + Lightning Design System = Great Apps
Angular2 workshop
Angular2 workshop
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
Getting Started with Angular 2
Getting Started with Angular 2
byFITC
Nativescript with angular 2
Nativescript with angular 2
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2
Advanced AngularJS Concepts
Advanced AngularJS Concepts

Similar to Intro to IndexedDB (Beta)

Save your data
PDF
Save your data
Academy PRO: HTML5 Data storage
PPTX
Academy PRO: HTML5 Data storage
Indexed db
ODP
Indexed db
Taking Web Apps Offline
PDF
Taking Web Apps Offline
Who's afraid of front end databases
PDF
Who's afraid of front end databases
Intro to HTML5 Web Storage
PDF
Intro to HTML5 Web Storage
Who's afraid of front end databases?
PDF
Who's afraid of front end databases?
Local Storage
PDF
Local Storage
Local storage in Web apps
PDF
Local storage in Web apps
IndexedDB - Querying and Performance
PPTX
IndexedDB - Querying and Performance
Local data storage for mobile apps
PDF
Local data storage for mobile apps
Client storage
PPTX
Client storage
Html indexed db
PPTX
Html indexed db
Whos afraid of front end databases?
PDF
Whos afraid of front end databases?
[2015/2016] Local data storage for web-based mobile apps
PDF
[2015/2016] Local data storage for web-based mobile apps
HTML5 Storage/Cache
PDF
HTML5 Storage/Cache
Freeing Yourself from an RDBMS Architecture
PPTX
Freeing Yourself from an RDBMS Architecture
Benefits of Using MongoDB Over RDBMSs
PPTX
Benefits of Using MongoDB Over RDBMSs
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
PPTX
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
HTML5 Data Storage
PPT
HTML5 Data Storage
Save your data
Save your data
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
Indexed db
Indexed db
Taking Web Apps Offline
Taking Web Apps Offline
Who's afraid of front end databases
Who's afraid of front end databases
Intro to HTML5 Web Storage
Intro to HTML5 Web Storage
Who's afraid of front end databases?
Who's afraid of front end databases?
Local Storage
Local Storage
Local storage in Web apps
Local storage in Web apps
IndexedDB - Querying and Performance
IndexedDB - Querying and Performance
Local data storage for mobile apps
Local data storage for mobile apps
Client storage
Client storage
Html indexed db
Html indexed db
Whos afraid of front end databases?
Whos afraid of front end databases?
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
HTML5 Storage/Cache
HTML5 Storage/Cache
Freeing Yourself from an RDBMS Architecture
Freeing Yourself from an RDBMS Architecture
Benefits of Using MongoDB Over RDBMSs
Benefits of Using MongoDB Over RDBMSs
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
HTML5 Data Storage
HTML5 Data Storage

Recently uploaded

Unveiling the Basics of Agentic AI - OSUG Mumbai
PDF
Unveiling the Basics of Agentic AI - OSUG Mumbai
Dr. Robert Krug - Specializes In Predictive Modeling
PDF
Dr. Robert Krug - Specializes In Predictive Modeling
Manage Files Using CLI - RHCSA (RH124).pdf
PDF
Manage Files Using CLI - RHCSA (RH124).pdf
Your First Deep Learning project With CNN (workshop).pptx
PPTX
Your First Deep Learning project With CNN (workshop).pptx
TrustArc Webinar - It’s Time to Rethink Privacy
PDF
TrustArc Webinar - It’s Time to Rethink Privacy
Wrapping up unowned UTF8 C strings: CStringView
PDF
Wrapping up unowned UTF8 C strings: CStringView
From Pixels to Insights: Getting Started with Imagery in FME
PDF
From Pixels to Insights: Getting Started with Imagery in FME
How Tridens DevSecOps Ensures Compliance, Security, and Agility
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
WebXR in Android and Linux with OpenXR
PDF
WebXR in Android and Linux with OpenXR
Transparency Exchange API: How Do You Find the SBOM for a Smart Light Bulb?
PDF
Transparency Exchange API: How Do You Find the SBOM for a Smart Light Bulb?
OutSystems ONE 2025-recap presentation.pptx
PPTX
OutSystems ONE 2025-recap presentation.pptx
Control Access to Files - RHCSA (RH124).pdf
PDF
Control Access to Files - RHCSA (RH124).pdf
Exclusive Hands-On Workshop: Agentic Automation with UiPath (First Edition)
PDF
Exclusive Hands-On Workshop: Agentic Automation with UiPath (First Edition)
RR B.Ed. educational trust. Ashish Tiwari
PDF
RR B.Ed. educational trust. Ashish Tiwari
The Smol Training Playbook: The Secrets to Building World-Class LLMs
PDF
The Smol Training Playbook: The Secrets to Building World-Class LLMs
Getting Started with MSP360 Backup for M365/Google
PPTX
Getting Started with MSP360 Backup for M365/Google
AWS re:Invent 2025 Event Presentation Slides
PDF
AWS re:Invent 2025 Event Presentation Slides
Private Governance: How Decentralized Mechanisms Can Regulate the Crypto Economy
PDF
Private Governance: How Decentralized Mechanisms Can Regulate the Crypto Economy
Save administrator time with the automated remediation capabilities of Red Ha...
PDF
Save administrator time with the automated remediation capabilities of Red Ha...
Access Linux File System in RHEL - RHCSA (RH124).pdf
PDF
Access Linux File System in RHEL - RHCSA (RH124).pdf
Unveiling the Basics of Agentic AI - OSUG Mumbai
Unveiling the Basics of Agentic AI - OSUG Mumbai
Dr. Robert Krug - Specializes In Predictive Modeling
Dr. Robert Krug - Specializes In Predictive Modeling
Manage Files Using CLI - RHCSA (RH124).pdf
Manage Files Using CLI - RHCSA (RH124).pdf
Your First Deep Learning project With CNN (workshop).pptx
Your First Deep Learning project With CNN (workshop).pptx
TrustArc Webinar - It’s Time to Rethink Privacy
TrustArc Webinar - It’s Time to Rethink Privacy
Wrapping up unowned UTF8 C strings: CStringView
Wrapping up unowned UTF8 C strings: CStringView
From Pixels to Insights: Getting Started with Imagery in FME
From Pixels to Insights: Getting Started with Imagery in FME
How Tridens DevSecOps Ensures Compliance, Security, and Agility
How Tridens DevSecOps Ensures Compliance, Security, and Agility
WebXR in Android and Linux with OpenXR
WebXR in Android and Linux with OpenXR
Transparency Exchange API: How Do You Find the SBOM for a Smart Light Bulb?
Transparency Exchange API: How Do You Find the SBOM for a Smart Light Bulb?
OutSystems ONE 2025-recap presentation.pptx
OutSystems ONE 2025-recap presentation.pptx
Control Access to Files - RHCSA (RH124).pdf
Control Access to Files - RHCSA (RH124).pdf
Exclusive Hands-On Workshop: Agentic Automation with UiPath (First Edition)
Exclusive Hands-On Workshop: Agentic Automation with UiPath (First Edition)
RR B.Ed. educational trust. Ashish Tiwari
RR B.Ed. educational trust. Ashish Tiwari
The Smol Training Playbook: The Secrets to Building World-Class LLMs
The Smol Training Playbook: The Secrets to Building World-Class LLMs
Getting Started with MSP360 Backup for M365/Google
Getting Started with MSP360 Backup for M365/Google
AWS re:Invent 2025 Event Presentation Slides
AWS re:Invent 2025 Event Presentation Slides
Private Governance: How Decentralized Mechanisms Can Regulate the Crypto Economy
Private Governance: How Decentralized Mechanisms Can Regulate the Crypto Economy
Save administrator time with the automated remediation capabilities of Red Ha...
Save administrator time with the automated remediation capabilities of Red Ha...
Access Linux File System in RHEL - RHCSA (RH124).pdf
Access Linux File System in RHEL - RHCSA (RH124).pdf

Intro to IndexedDB (Beta)

  • 1.
    IndexedDB Mike West @mikewest, mkwst@google.com SV GTUG, 2010年12月14日
  • 2.
    A IndexedDB T ] [ B E Mike West @mikewest, mkwst@google.com
  • 3.
  • 4.
  • 5.
  • 6.
    Simple, key/value pairs, Cookies "shared" between server and client. • Excellent for maintaining state, poor for anything else, as they are unstructured, and incur a significant overhead for each HTTP request.
  • 7.
    Local Storage http://www.flickr.com/photos/photohome_uk/1494590209/
  • 8.
    Local Storage • The simplicity of cookies, tuned for higher-capacity, client-side-only storage. • Dead simple API: localStorage.setItem( ‘key’, ‘value’ ); localStorage.getItem( ‘key’ ); // ‘value’ • Values are unstructured strings: • Filtering and search are O(n), unless you layer some indexing on top. • Structure requires JSON.stringify & JSON.parse
  • 9.
  • 10.
    WebSQL • A real, relational database implementation on the client (SQLite) • Data can be highly structured, and JOIN enables quick, ad-hoc access • Big conceptual overhead (SQL), no finely grained locking • Not very JavaScripty, browser support is poor, and the spec has been more or less abandoned.
  • 11.
    File API http://www.flickr.com/photos/daddo83/3406962115/
  • 12.
  • 13.
  • 14.
    IndexedDB • Sits somewhere between full-on SQL and unstructured key-value pairs in localStorage. • Values are stored as structured JavaScript objects, and an indexing system facilitates filtering and lookup. • Asynchronous, with moderately granular locking • Joining normalized data is a completely manual process.
  • 15.
  • 16.
    Practically everything is asynchronous. Callbacks are your friends.
  • 17.
    Databases are named, and contain one or more named Object Stores
  • 18.
  • 19.
    Object Stores define a property which every stored object must contain, explicitly or implicitly.
  • 20.
    contacts 1 2 3 4 5 6 7 8 9
  • 21.
    Values in an Object Store are structured, but don’t have a rigidly defined schema.
  • 22.
    contacts 1 2 3 4 5 6 7 8 9
  • 23.
    Object Stores can contain one or more Indexes that make filtering and lookup possible via arbitrary properties.
  • 24.
    contacts 1 2 3 4 5 6 7 8 9
  • 25.
  • 26.
    T A ] [ B E IndexedDB API
  • 27.
  • 28.
    // Deal with vendor prefixes if ( "webkitIndexedDB" in window ) { window.indexedDB = window.webkitIndexedDB; window.IDBTransaction = window.webkitIDBTransaction; window.IDBKeyRange = window.webkitIDBKeyRange; // ... } else if ( "moz_indexedDB" in window ) { window.indexedDB = window.moz_indexedDB; } if ( !window.indexedDB ) { // Browser doesn’t support indexedDB, do something // clever, and then exit early. }
  • 29.
    Database creation is asynchronous
  • 30.
    var dbRequest = window.indexedDB.open( "AddressBook", // Database ID "All my friends ever" // Database Description ); // The result of `open` is _not_ the database. // It’s a reference to the request to open // the database. Listen for its `success` and // `error` events, and respond appropriately. dbRequest.onsuccess = function ( e ) { ... }; dbRequest.onerror = function ( e ) { ... };
  • 31.
  • 32.
    // The `result` attribute of the `success` event // holds the communication channel to the database dbRequest.onsuccess = function ( e ) { var db = e.result; // Bootstrapping: if the user is hitting the page // for the first time, she won’t have a database. // We can detect this by inspecting the database’s // `version` attribute: if ( db.version === "" ) { // Empty string means the database hasn’t been versioned. // Set up the database by creating any necessary // Object Stores, and populating them with data // for the first run experience. } else if ( db.version === "1.0" ) { // 1.0 is old! Let’s make changes! } else if ( db.version === "1.1" ) { // We’re good to go! } // ... };
  • 33.
    ... and versioning is asynchronous.
  • 34.
    dbRequest.onsuccess = function ( e ) { var db = e.result; if ( db.version === "" ) { // We’re dealing with an unversioned DB. Versioning is, of // course, asynchronous: var versionRequest = db.setVersion( "1.0" ); versionRequest.onsuccess = function ( e ) { // Here’s where we’ll set up the Object Stores // and Indexes. }; } // ... };
  • 35.
  • 36.
    dbRequest.onsuccess = function ( e ) { var db = e.result; if ( db.version === "" ) { var versionRequest = db.setVersion( "1.0" ); // Setting a version creates an implicit Transaction, meaning // that either _everything_ in the callback succeeds, or // _everything_ in the callback fails. versionRequest.onsuccess = function ( e ) { // Object Store creation is atomic, but can only take // place inside version-changing transaction. var store = db.createObjectStore( "contacts", // The Object Store’s name "id", // The name of the property to use as a key true // Is the key auto-incrementing? ); // ... }; } // ... };
  • 37.
    dbRequest.onsuccess = function ( e ) { var db = e.result; if ( db.version === "" ) { var versionRequest = db.setVersion( "1.0" ); versionRequest.onsuccess = function ( e ) { var store = db.createObjectStore( "contacts", "id", true ); store.createIndex( "CellPhone", // The index’s name "cell", // The property to be indexed false // Is this index a unique constraint? ); }; } // ... };
  • 38.
    Writing Data (is asynchronous)
  • 39.
    // Assuming that `db` has been set somewhere in the current // scope, we use it to create a transaction: var writeTransaction = db.transaction( [ "contacts" ], // The Object Stores to lock IDBTransation.READ_WRITE // Lock type (READ_ONLY, READ_WRITE) ); // Open a contact store... var store = writeTransaction.objectStore( "contacts" ); // ... and generate a write request: var writeRequest = store.add( { "name": "Mike West", "email": "mkwst@google.com" } ); writeRequest.onerror = function ( e ) { writeTransaction.abort(); }; // Transactions are "complete" (not "committed"?) either when // they fall out of scope, or when all activities in the // transaction have finished (whichever happens last) writeTransaction.oncomplete = function ( e ) { ... };
  • 40.
    Reading Data (is asynchronous)
  • 41.
    // Assuming that `db` has been set somewhere in the current // scope, we use it to create a transaction: var readTransaction = db.transaction( [ "contacts" ], // The Object Stores to lock IDBTransation.READ_ONLY // Lock type (READ_ONLY, READ_WRITE) ); // Open the `contact` store... var store = readTransaction.objectStore( "contacts" ); // ... and generate a cursor to walk the complete list: var readCursor = store.openCursor(); // Setup a handler for the cursor’s `success` event: readCursor.onsuccess = function ( e ) { if ( e.result ) { // You now have access to the key via `e.result.key`, and // the stored object via `e.result.value`. For example: console.log( e.result.value.email ); // mkwst@google.com } else { // If the `success` event’s `result` is null, you’ve reached // the end of the cursor’s list. } };
  • 42.
  • 43.
    var t = db.transaction( [ "contacts" ], IDBTransation.READ_ONLY ); var s = t.objectStore( "contacts" ); // ... and generate a cursor to walk a bounded list, for example // only those names between M and P (inclusive) var bounds = new IDBKeyRange.bound( "M", // Lower bound "Q", // Upper bound true, // Include lower bound? false // Include upper bound? ); var readCursor = store.openCursor( bounds ); // Setup a handler for the cursor’s `success` event: readCursor.onsuccess = function ( e ) { // process `e.result` };
  • 44.
    Further Reading The IndexedDB Spec: http://www.w3.org/TR/IndexedDB/ "Firefox 4: An Early Walkthrough of IndexedDB": http://hacks.mozilla.org/2010/06/comparing- indexeddb-and-webdatabase/ Mozilla Developer Docs: https://developer.mozilla.org/en/IndexedDB
  • 45.
    Questions? Mike West @mikewest mkwst@google.com http://mikewest.org/

Editor's Notes

  • #2 \n
  • #3 This stuff is completely beta at the moment. It’s only implemented in Firefox 4 and Chrome dev channel, so it’s not anything that can be used for production projects in the near future. Microsoft and Opera are contributing to the spec, however, and Google is working on pushing the code upstream to Webkit itself, so this looks like something that will be more and more relevant going forward. \n\nSince the spec’s not finished, and everything’s in dev mode, this is a _great_ time to examine the API, and experiment. We need to play around with this code, and feed our experience back into the standards bodies and browser vendors: that’s the best way to ensure that things work the way we want them to when everything’s solidified.\n
  • #4 One of the most exciting recent realizations in web development is that the offline bits of the HTML5 suite of specifications are _really ready_ for widespread use. It's possible to store arbitrary amounts of information on a user's computer without resorting to opaque hacks like Flash storage, while at the same time making that information available in useful ways to your program's code. This opens up a whole new world of sites and applications which we're only just beginning to appreciate. Offline's important, and not just because of the Web Store.\n\n
  • #5 What I'd like to do here is take a very brief survey of the landscape for context, and then dive into one particular feature that I think will become important in the near future: IndexedDB.\n\n
  • #6 These aren’t even offline, but let’s take a quick look at why they’re not enough. :)\n
  • #7 \n
  • #8 \n
  • #9 This is probably the best way to start with offline storage, as the API’s trivial. You’ll have to build your own indexing solution, however, which might be a bit more work than you were looking for.\n
  • #10 Yes, stacking many file cabinets on top of each other is a nice way to increase your storage, at the expense of complexity (you’ll need ladders), and danger (you might fall off). That’s pretty much how I feel about WebSQL.\n
  • #11 \n
  • #12 \n
  • #13 I know nothing about the File API, but Seth’s going to tell us all about it shortly. I’ll be all ears. :)\n
  • #14 \n
  • #15 \n
  • #16 \n
  • #17 \n
  • #18 \n
  • #19 \n
  • #20 \n
  • #21 \n
  • #22 \n
  • #23 \n
  • #24 \n
  • #25 \n
  • #26 \n
  • #27 \n
  • #28 \n
  • #29 \n
  • #30 \n
  • #31 \n
  • #32 \n
  • #33 \n
  • #34 \n
  • #35 \n
  • #36 \n
  • #37 \n
  • #38 \n
  • #39 \n
  • #40 \n
  • #41 \n
  • #42 \n
  • #43 \n
  • #44 \n
  • #45 \n
  • #46 \n

AltStyle によって変換されたページ (->オリジナル) /