html5 für entwickler: part 1, 2 und 3, 2013
DESCRIPTION
Und hier der dritte und abschließende Teil zum Thema Javascript mit Demos zu den API: Canvas, Geolocation, Device Orientation, Notifications, WebSockets, Worker, Storage, Web SQL, Indexed DB und File API.TRANSCRIPT
Kochan & PartnerBrandDesignDevelopment
HTML5 für Entwickler
Markus Greve
Für den Abendkurs der Typographischen
Gesellschaft München, 2013
markup, noun. A markup language is a modern
system for annotating a document in a way that is
syntactically distinguishable from the text. The idea
and terminology evolved from the »marking up« of
manuscripts
—Wikipedia
Kochan & Partner Brand Design Development2
Demos, Links, Ressourcen http://www.kochan.de/html5Slides http://de.slideshare.net/markusgreve/
Markus Greve KOCHAN & PARTNER BRAND DESIGN DEVELOPMENT
T +49 89 17860–150 E [email protected] @mrmontezuma
Kochan & Partner Brand Design Development
Organisatorisches
3
28.02. Einführung Hidden Gems Part 1: Markup
07.03. Part 2: CSS
14.03. Part 3: Javascript
21.03. Hack-a-thon: Thema offen!
Kochan & Partner Brand Design Development
Hack-A-Thon
4
Themenvorstellung, Gruppenbildung ca. 15min
Gruppen von 2 – 3 Personen, d.h. 4 – 5 Gruppen
Hacking ca. 120min
Standup 5min pro Gruppe: Vorstellung
Kochan & Partner Brand Design Development5
Kochan & Partner Brand Design Development
Was ist HTML5 und was nicht
6
...Quelle: Peter Kröner, http://html5-buch.deCreative Commons Namensnennung 3.0 Deutschland-Lizenz
Kochan & Partner Brand Design Development
Was ist HTML5?
7
HTML 4.01
XHTML 1
W3C, WHATGC
Nicht-Standard wird Standard
Kochan & Partner Brand Design Development
Was ist HTML5?
8
Semantic
Quelle: http://www.w3.org/html/logo/
Offline & Storage
DeviceRealtime &
Communication
Multimedia3D, Graphics
& EffectsPerformance &
IntegrationCSS3
Kochan & Partner Brand Design Development
Unterstützung
9
Kochan & Partner Brand Design Development
Can I Use?
10
Suche
Volle/teilweise Unterstützung
Detaillierte Versionsinfo
Weiterführende Informationen, Referenz
Quelle: http://caniuse.com
Kochan & Partner Brand Design Development
HTML5 & CSS3, findmebyIP
11
CSS3 Properties
CSS3 Selectors
Web Applications
Graphics & embedded Content
Audio codecs
Video codecs
WebForms 2.0
Quelle: http://www.findmebyip.com/litmus/
Kochan & Partner Brand Design Development
Strategie
12
Graceful degredation
Progressive enhancement
Kochan & Partner Brand Design Development
Hilfsmittel
13
Polyfills
Kochan & Partner Brand Design Development
IE–Quickfix (1)
14
window.document.createElement('section');
Kochan & Partner Brand Design Development
IE–Quickfix (2)
15
Sinngemäße Quelle:: http://code.google.com/p/html5shiv/
'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup menu mark meter nav output progress section summary time video'.replace(/w+/g,function(n){window.document.createElement(n)});
Kochan & Partner Brand Design Development
Standard Stylesheet Hack
16
command, datalist, source { display: none; }
article, aside, figcaption, figure, footer, header,hgroup, menu, nav, section, summary
{ display: block; }
mark { background: #FF0; color: #000; }
Sinngemäße Quelle:: http://code.google.com/p/html5shiv/
Kochan & Partner Brand Design Development
normalize.css
17
A modern, HTML5-ready alternative to CSS resets used by Twitter Bootstrap, HTML5 Boilerplate and many more.
Quelle: http://necolas.github.com/normalize.css/
Kochan & Partner Brand Design Development
Modernizr
18
The All-In-One Entirely-Not-Alphabetical No-Bullshit Guide to HTML5 Fallbacks
—Modernizr
Quelle: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
SVG
Canvas
Web Storage
Video & Audio
IndexedDB, WebSQL
WebForms
Accessiblity / ARIA
Web Sockets
Geo Location
Application Cache
Browser State Management
....
Kochan & Partner Brand Design Development
–prefix–free
19
–prefix–free lets you use only unprefixed CSS properties everywhere. It works behind the scenes, adding the current browser’s prefix to any CSS code, only when it’s needed.
—Lea Verou
Quelle: http://leaverou.github.com/prefixfree/
Kochan & Partner Brand Design Development20
»Hidden Gems«
Kochan & Partner Brand Design Development
Standard-Typen für script und style
21
type=“text/javascript“ language=“javascript“
Standard-Wert für das script-Tag
type=“text/javascript“
Standard-Wert für das style-Tag
Kochan & Partner Brand Design Development
Skript-Ausführungsverhalten mit defer, async
22
Beispiel
<script defer> // code that runs after DOM finished loading // ...</script>
<script async> // code that runs in the background // not blocking other scripts // ...</script>
Kochan & Partner Brand Design Development
a, area und link (1)
23
<a target=“_blank“>Link ohne Ziel und Verstand</a>
<a href=“http://www.google.de“ rel=“prefetch“>Descriptiver Rel-Einsatz
</a>
Vereinheitlichung von a, area und link
Umschließung
Wiederbelebung target, optionales href-Attribut
Typisierung mittels rel
Beispiel
Kochan & Partner Brand Design Development
a, area und link (2)
24
Umfangreiches Set an Schlüsselworten für rel:
Navigation, Strukturierung index, first, last, prev, next, up
Inhaltlich author, alternate, archives, bookmark, external, help, license, pingback, search, tag
Beeinflussung Browser-Verhalten sidebar, prefetch, nofollow, noreferrer
Typisierend icon, stylesheet
Kochan & Partner Brand Design Development
Fokus
25
<input type="text" name="search" autofocus />
Auto-Fokus erlaubt für input, select, textarea und button
Standardisierung der Fokus-Ermittlung
Auto-Fokus
if (document.hasFocus()){
var element = document.activeElement();}
Fokus-Ermittlung
Kochan & Partner Brand Design Development
Einbindung svg und MathML (1)
26
<!DOCTYPE html>...
<body><svg width="300" height="150">
<rect width="120" height="120"fill="green"stroke="red" stroke-width="10" />
<circle cx="120" cy="65" r="40"
fill="red"stroke="green"stroke-width="5" />
</svg></body>
...
<!DOCTYPE html>...
<body><math>
<mrow><mi>x</mi><mo>=</mo><mfrac>
<mrow><mo form="prefix">
±</mo><mi>b</mi><mo>±</mo><msqrt>
<msup><mi>b</mi> <mn>2</mn>
</msup> <mo>-</mo><mn>4</mn>...
Kochan & Partner Brand Design Development
Einbindung svg und MathML (2)
27
Screenshots: Safari 6/Mac OS X
Kochan & Partner Brand Design Development
WYSIWYG und Rechtschreibhilfe
28
<div id="myEditor" contenteditable="true" spellcheck="false">...</div>
element.isContentEditabledocument.designMode = 'on';
Beispiele
Mögliche Werte für contenteditable und spellcheck:
true, false, inherit
Kochan & Partner Brand Design Development
Standardisierung getElementsByClassName()
29
document.getElementsByClassName()element.getElementsByClassName()
API
var allMyActiveDivs = document.getElementsByClassName('active');
var myOtherLis = myUl.getElementsByClassName('inactive');
Beispiele
Kochan & Partner Brand Design Development
HTML-Manipulation
30
element.innerHTMLelement.outerHTMLelement.insertAdjacentHTML(<position>, <html>) <position> := 'beforebegin' 'afterbegin' 'beforeend' 'afterend'
API
myUl.innerHTML = '<li>New Bullet</li>';myUl.outerHTML = '<ul><li>New Bullet</li></ul>';
myLi.insertAdjacentHTML('beforebegin', '<li>Vorgänger</li>');
Beispiele
Kochan & Partner Brand Design Development
Class List API
31
element.classList.length .add() .contains() .item() .remove() .toggle()
API
myDiv.classList.add('active'); // 'active' is addedmyDiv.classList.remove('active'); // 'active' is removedmyDiv.classList.toggle('active'); // add or remove
if (myDiv.classList.contains('active')) alert('Aktiv!')
Beispiele
Kochan & Partner Brand Design Development
Query-Selector API
32
document.querySelector(<CSS Selector>); // first matchdocument.querySelectorAll(<CSS Selector>); // all matches
var oddRows = document.querySelectorAll('#table > tr:nth-child(odd)');
Randnotiz: w3C Standard seit vergangenem Freitag, 22. Februar 2013
Beispiel
API
Kochan & Partner Brand Design Development
Frei definierbare Attribute: data-*
33
Attribute data-*
API element.dataset
<a data-file-type="pdf" data-file-size="73" href="...">Preisliste und Kundenheft
</a>
// data-* will become dataset-Members, notice "Camel" writingalert(element.dataset.fileType) // alerts "pdf"alert(element.dataset.fileSize) // alerts "73"
Beispiel
Kochan & Partner Brand Design Development
History API
34
history.length .back() .forward() .go(<delta>) .state .pushState(<stateObj>, <title>, <url>) .replaceState()
window.onpopstate = function(e) { // code to be executed after browser-back button // ...};
API
Kochan & Partner Brand Design Development
Zusammenfassung: Markup
35
Standard-Type für script und style
Skript-Ausführungsverhalten mit defer, async
Fokus-Behandlung mit autofocus, hasFocus() und activeElement()
a, area und link: Vereinheitlichung, Umschließung, Typisierung mit rel
SVG und MathML
WYSIWYG und Rechtschreibhilfe
Brand Design Development
Kochan & Partner Brand Design Development
Zusammenfassung: Javascript
36
HTML-Manipulation mittels innerHTML, outerHTML, insertAdjacentHTML
Standardisierung getElementsByClassName()
ClassList API
Query Selector API
Frei definierbare Attribute mit data-*
History API
Brand Design Development
Kochan & Partner Brand Design Development37
Part 1Markup
Kochan & Partner Brand Design Development38
SemantikFormulareVideo & AudioApplication Cache
Kochan & Partner Brand Design Development39
SemantikFormulareVideo & AudioApplication Cache
Kochan & Partner Brand Design Development
Grundgerüst
40
<!DOCTYPE html><html>
<head><meta charset=“utf-8“/><title>Hello world</title>
</head><body>
<h1>Hello world</h1><p>Starting with HTML5</p>
</body></html>
Kochan & Partner Brand Design Development
DOCTYPE
41
<!DOCTYPE html><html>
<head><meta charset=“utf-8“/><title>Hello world</title>
</head><body>
<h1>Hello world</h1><p>Starting with HTML5</p>
</body></html>
Kochan & Partner Brand Design Development
Auslassung
42
<!DOCTYPE html><html>
<head><meta charset=“utf-8“/><title>Hello world</title>
</head><!-- -->
<h1>Hello world</h1><p>Starting with HTML5</p>
<!-- --></html>
Kochan & Partner Brand Design Development
Well-formed oder nicht? Egal!
43
<!DOCTYPE html><html>
<head><meta charset=“utf-8“ ><title>Hello world</title>
</head><body>
<h1>Hello world</h1><p>Starting with HTML5<p> ... <a href=index.html>No quotation marks!</a> <STRONG>You don't have to like this</STRONG> <eM>I don't</Em>
</body><html>
Kochan & Partner Brand Design Development
Neue Elemente
44
Kopf- und Fußbereiche header, footer
Seitenabschnitte section
Artikel article
Navigationsbereiche nav
Begleitende Informationen aside
Abbildungen figure, figcaption
Markierung mark
Kochan & Partner Brand Design Development
Neue Elemente (2)
45
Uhrzeit time
Menü menu
Button/Checkbox/Radiobox command
Fortschrittsanzeige progress
Skala meter
Detailansicht details
Zusammenfassung einer Detailansicht summary
Kochan & Partner Brand Design Development
Kopf- und Fußbereich: header, footer
46
Kopfbereich z.B. für Logo, Navigationsbereich
Beide Elemente pro Seite und pro Sektion definierbar
<header><a href="index.html" rel="index">Huber GmbH</a><nav>...</nav>
</header>
...
<footer> © 2013 <a href="imprint.html" rel="author">Huber GmbH</a> <a href="license.html" rel="license">Nutzungsbedingungen</a></footer>
Kochan & Partner Brand Design Development
Artikel und Sinnabschnitte: article und section
47
Zusammenfassung inhaltlich abgeschlossener Bereiche durch article
Inhaltliche Strukturierung der Seite bzw. des Artikels durch section
<body>
<article>
<article>...
<article>...
<section class="intro">
<section class="copy">
Kochan & Partner Brand Design Development
Artikel und Sinnabschnitte: article und section
48
Zusammenfassung inhaltlich abgeschlossener Bereiche durch article
Inhaltliche Strukturierung der Seite bzw. des Artikels durch section
<body>
<article>
<article>...
<article>...
<section class="intro">
<section class="copy">
Kochan & Partner Brand Design Development
Navigationsbereiche: nav
49
Kennzeichnung der Hauptnavigationsbereiche als nav
Nebennavigationen außerhalb, z.B. Meta-Navigation im footer
...<nav> <ul> <li><a href="news.html">News</a></li> <li><a href="about.html">Über uns</a></li> <li>...</li> </ul></nav>...<a href="imprint.html">Impressum</a>
Kochan & Partner Brand Design Development
Begleitende Informationen: aside
50
Innerhalb eines articles: sekundärer Inhalt in Bezug auf den Artikel
Außerhalb eines articles: sekundärer Inhalt in Bezug auf die Website als Ganzes
<body>
<article>
<section>
<aside> Verwandte Themen
Ganz andere Themen
...
</aside>
<section>
<aside> Mehr zu diesem Thema
</aside>
Kochan & Partner Brand Design Development
Abbildungen: figure und figcaption
51
Semantische Einheit für eine Abbildung figure, z.B. ein Bild, eine Tabelle oder ein Diagramm, mit optionaleer Abbildungsbeschriftung figcaption.
Reihenfolge der Darstellung kann ohne Verständnisverlust verändert werden.
<body>
<article>
<section>
<figure> <img src=""... /> <svg... /> <figcaption> Quelle: BMW AG. </figcaption></figure>
<section>
Kochan & Partner Brand Design Development
Zeitangaben: time
52
Maschinenlesbare Kodierung von Zeitangaben des proleptischen Gregorianischen Kalenders
Datumsangabe, Uhrzeit oder eine Kombination aus Datum und Uhrzeit
optional: Kennzeichnung als Veröffentlichungszeitangabe
Das <time datetime="2013-02-28">heutige</time> Seminar...
Jeden Tag um <time datetime="12:00">12</time> Uhr...
<time datetime="2013-03-01T17:00Z">Morgen um fünf</time>...
Veröffentlicht am: <time datetime="2013-02-26" pubdate> 26.02.13</time>
Beispiele
Kochan & Partner Brand Design Development
Markierung: mark
53
Hervorhebung von Text ohne inhaltliche Betonung
Nutzbar insbesondere (ausschließlich?) für Suchergebnisse (SERP)
<h1>Ihre Suche nach <em>entertain</em>:</h1><ul> <li>Let me <mark>entertain</mark> you: Queen, Jazz, 1978</li> <li>That's <mark>Entertain</mark>ment: Band Waggon, 1953</li></ul>
Beispiel
Ihre Suche nach entertain:
• Let me entertain you: Queen, Jazz, 1978
• That's Entertainment: Band Waggon, 1953
Kochan & Partner Brand Design Development
Fortschrittsanzeige: progress
54
Darstellung Betriebssystem-spezifisch
Maximum (max) und aktueller Status (value) optional via numerischem Wert
Aktueller Fortschriftt via element.position (0.0 – 1.0, –1 bei unbekannt)
Safari 6/Mac OS X
Firefox 10 /Windows Non-Aqua
Internet Explorer/Windows Phone 8
Kochan & Partner Brand Design Development
Skala: meter
55
Darstellung Betriebssystem-spezifisch
Grenzen (min, max) und aktuellem Wert (value) optional via numerischem Wert
Einfärbung bei Erreichen von Schwellwerten (low, high, optimum) möglich
Safari 6/Mac OS X
Kochan & Partner Brand Design Development
Outline-Algorithmus (1)
56
Beibehaltung des 6-stufiges Überschriften-Modell h1 bis h6
Hierarchie jedoch pro Sektion
Sektionen definiert durch section, nav, aside und article
Kochan & Partner Brand Design Development
Outline-Algorithmus (2)
57
<h1>Agenda</h1><section> <h1>Begrüßung</h1> <h2>Schirmherr</h2> <h2>Sponsorenvertreter</h2> <h1>Top 1: Gruppen</h1> <h1>Top 2: Plenung</h1></section><h1>Anlagen</h1>
Beispiel
1. Agenda
1.1 Begrüßung
1.1.1 Schirmherr
1.1.2 Sponsorenvertreter
1.2 Top 1: Gruppen
1.3 Top 2: Plenum
2. Anlagen
Kochan & Partner Brand Design Development
Umdeutung/Änderung bestehender Elemente
58
Hervorhebung em, strong
Abkürzung und Akronym abbr
Quellcode code
Adresse address
Gleichwertige Abhebung, Fachbegriffe b, i
Inhaltlicher Bruch hr
»Kleingedrucktes« small
Kochan & Partner Brand Design Development
Entfernte Elemente
59
Frames frameset, frame, noframes
Präsentationselementedir, basefont, big, center, font, s, strike, tt, u
Akronyme acronym
Applets applet
Einzeiliges Eingabefeld (?) isindex
Randnotiz: HTML5 definiert, wie diese nicht spezifizierten Elemente dargestellt werden sollen... :-)
Kochan & Partner Brand Design Development60
AR IA
Kochan & Partner Brand Design Development61
AccesibleRich InternetApplication
Kochan & Partner Brand Design Development
WAI-ARIA
62
Implizite Rollen
Definierte Überschreibbarkeit
Explizite Attribute: Rollen, Beschriftungen, Zustände, ...
Kochan & Partner Brand Design Development
Implizite Rollen und Überschreibung
63
Element Default role Überschreibbar mit
article article document, application, main
aside note complementary, search
header keine banner
li listitem treeitem
ol list tree, directory
output status Alle
section region document, application, log, contentinfo, search, alert, main, dialog, alertdialog, status, log
table grid treegrid
ul list tree, directory
body document application
Kochan & Partner Brand Design Development
Explizite Rollenzuweisung
64
<ul role="tree" aria-labelledby="Credits">
<li role="treeitem" aria-expanded="false"> John Deacon: Bass guitar </li> <li role="group"> Freddie Mercury: <ul> <li role="treeitem">Vocals</li> <li role="treeitem">Piano</li> </ul> </li> ...</ul>
Details: http://w3.org/TR/wai-aria/
Kochan & Partner Brand Design Development
Microdata
65
RDFa
microformats.org
HTML5-Microdata: vCard, vEvent, work
Attribute itemscopeitempropitemref
API document.getItems()element.propertieselement.itemValue
Kochan & Partner Brand Design Development
Microdata: Google Rich Snippets
66
Quelle: http://support.google.com/webmasters/bin/answer.py?hl=de&answer=99170
Kochan & Partner Brand Design Development
Microdata: Google Rich Snippets (2)
67
Quelle: http://www.google.com/webmasters/tools/richsnippet
Kochan & Partner Brand Design Development
Zusammenfassung: Semantik
68
Syntax: doctype, well formed, Auslassung
Neue Elemente
Umdeutung/Änderung bestehender Elemente
Entfernte Elemente
Outline-Algorithmus
WAI-ARIA
Microdata
Brand Design Development
Kochan & Partner Brand Design Development69
SemantikFormulareVideo & AudioApplication Cache
Kochan & Partner Brand Design Development
Neue Typen für input (1)
70
Textfeld text
Suchfeld search
Telefonnummer telephone
URL* url
E-Mail-Adresse* email
Numerischer Wert* number
Bereich* range
Farbwahl / Color picker color
* Eingebaute Validierung
Kochan & Partner Brand Design Development
Neue Typen für input (2)
71
Datum- und Zeit-Angaben datetime
Datum date
Monat month
Woche week
Zeit time
Datum- und Zeit in lokaler Notation datetime-local
Kochan & Partner Brand Design Development
Typ number, range
72
Eingabefeld oder Regler für Fließkomma-Zahlen
optional: Grenzen (min, max) und Schrittweite (step)
<input type="number" min="-10" max="87" step="1" /><input type="range" min="-10" max="87" step="1" />
Beispiele
Safari 6/Mac OS X
IE 10/WIndows 8
Kochan & Partner Brand Design Development
Typ search
73
Eingabefeld für Suchen
Darstellung nach Art des Betriebssystems
<input type="search" placeholder="Suche" />
Beispiel
Safari 6/Mac OS X
Kochan & Partner Brand Design Development
Typ Farbwahl / Colorpicker color
74
Leider noch kaum implementiert
<input type="color" />
Beispiel
Chrome 25/Mac OS X
Opera 12/Mac OS X
Kochan & Partner Brand Design Development
Typ für Datum- und Zeitangaben
75
Validierung, optional mit Beschränkung min und max
<input type="datetime" /><input type="date" /><input type="month" /><input type="week" /><input type="time" /><input type="datetime-local" />
Beispiele
Chrome 25/Mac OS X
Kochan & Partner Brand Design Development
Neue Elemente
76
Erzeugung von Schlüsseln keygen
Objekt object
Ausgabebereich output
Auto-Vervollständigung datalist
Kochan & Partner Brand Design Development
Auto-Vervollständigung: datalist
77
<input list="albums" />
<datalist id="albums"> <option value="Queen" /> <option value="Queen II" /> <option value="Sheer Heart... <option value="A Night At ... <option value="A Day At Th... <option value="The Game" ... <option value="The Works" /> <option value="A kind of m... <option value="The Miracle" <option value="Innuendo" /> ...
Beispiel
Chrome 25/Mac OS X
Kochan & Partner Brand Design Development
Neue Attribute
78
Referenz auf zugehöriges Formular form
Steuerung Auto-Vervollständigung autocomplete
Referenz auf Vorschlagsliste list
Mehrfach-Feld (z.B. bei Datei-Upload) multiple
Platzhalter / Eingabehilfe placeholder
Checkbox mit unbekanntem Zustand indeterminate
Steuerung Button-Verhalten formaction, formenctype, formmethod, formnovalidate
Kochan & Partner Brand Design Development
Steuerung Button-Verhalten
79
<form action="standard.php" method="post"> <button type="submit">Absenden</button> <button type="submit" formaction="alternate.php"> Anderswohin </button> <button type="submit" formnovalidate>Ohne Prüfung</button></form>
Beispiel
Absenden Anderswohin Ohne Prüfung
standard.php alternate.php standard.php
ValidierungPost
ValidierungPost
keine ValidierungPost
Kochan & Partner Brand Design Development
Validierung
80
Validierung auf Ebene Element, Feldgruppe oder Formular
Keine Validierung für hidden, submit, image, reset und object
CSS Pseudo-Selektoren für Styling :in-range, :default, :required
Fehlermeldung bei Absenden des Formulars oder manuell via Javascript API
Beeinflussung durch Attribute novalidate, required und patternz.B. pattern="[0-9]{5}"
Kochan & Partner Brand Design Development
Validation API
81
MemberMember
Bool'scher Wert element.willValidate
Lokalisierte Fehlermeldung element.validationMessage
Datenstruktur zur Fehleranalyse element.validity .valid .valueMissing .typeMismatch .patternMismatch .tooLong .rangeUnderflow .rangeOverflow .stepMismatch .customError
MethodenMethoden
Validierung auslösen element.checkValidity()
Eigene Regel setzen element.setCustomValidity()
Kochan & Partner Brand Design Development82
BrowserUnterstützung?
Kochan & Partner Brand Design Development83
Mac OS X
Kochan & Partner Brand Design Development84
Windows 8
Kochan & Partner Brand Design Development85
iOS (1)
Kochan & Partner Brand Design Development86
iOS (2)
Kochan & Partner Brand Design Development87
Windows Phone 8
Kochan & Partner Brand Design Development
Zusammenfassung: Formulare
88
Neue Typen für input
Neue Elemente und Attribute
Validierung und Validation API
Browser-Unterstützung
Brand Design Development
Kochan & Partner Brand Design Development89
SemantikFormulareVideo & AudioApplication Cache
Kochan & Partner Brand Design Development
Audio- und Video-Einbindung
90
Steuerelemente an/abschaltbar mit controls (»Headless«)
Alternativer Inhalt innerhalb des Elements
Umfangreiche Javascript API zur Steuerung
<audio src="queen-a-day-at-the-races.ogg" controls> Leider unterstützt ihr Browser das audio-Element nicht. Klicken Sie hier, um die <a href="queen-a-day-at-the- races.ogg">Datei herunterzuladen</a>. </audio>
Beispiel
Kochan & Partner Brand Design Development
Audio-Attribute
91
<audio src="audio.ogg#t=10,20" controls autoplay preload="auto" loop> ...</audio>
Beispiel
Quellenangabe: src, hier mit Framestart und -ende #t=
Steuerelemente: controls
Automatisches abspielen: autoplay
Preload-Verhalten: none, metadata, auto
Wiederholte Wiedergabe: loop
Kochan & Partner Brand Design Development
Video-Attribute
92
<video src="video.ogg" controls autoplay preload="auto" loop width="640" height="480" audio="muted" poster="videoframe.jpg"> ...</video>
Beispiel
Quellenangabe: src
Steuerelemente: controls
Automatisches abspielen: autoplay
Preload-Verhalten: none, metadata, auto
Wiederholte Wiedergabe: loop
Dimensionen: width und height
Audio-Steuerung: audio="muted"
Thumbnail: poster
Kochan & Partner Brand Design Development
Multiple Quellen: Codecs
93
<video> <source src="video.ogg" /> <source src="video.mp4" /></video>
Implizite Ermittlung via Mime-Type
<video> <source src="video.ogg" type="video/ogg; codecs='theora, vorbis'" /> <source src="video.mp4" type="video/mp4" /></video>
Explizite Vorgabe
Kochan & Partner Brand Design Development
Multiple Quellen: Devices
94
<video> <source src="small.ogg" media="handheld" /> <source src="high-res.ogg" media="all" /></video>
Media-spezifisch
Kochan & Partner Brand Design Development
Audio- und Video API: Member
95
Lautstärke (0 – 1) element.volume
Pausiert (true, false) element.paused
Ton ausgeblendet (true, false) element.muted
Position auslesen und setzen element.currentTime
Aktuelle Mediendatei element.currentSrc
Abspieldauer (Streams: 'infinity') element.duration
Startzeitpunkt element.startTime
Normale Abspielgeschwindigkeit (0 – 1) member.defaultPlaybackRate
Abspielgeschwindigkeit (0 – 1) member.playbackRate
Kochan & Partner Brand Design Development
Audio- und Video API: TimeRanges
96
MemberMember
(Bereits) Durchsuchbarer Zeitraum element.seekable
Abgespielter Zeitraum element.played
Vorgelden (gepufferter) Zeitraum element.buffered
[TimeRangeObject][TimeRangeObject]
Anzahl der definierten Zeiträume timerange.length
Startzeitpunkt von Zeitraum n timerange.start(n)
Endzeitpunkt von Zeitraum n timerange.end(n)
Kochan & Partner Brand Design Development
Audio- und Video API: Methoden
97
Abspielen element.play()
Pausieren element.pause()
Mediendatei laden element.load(<url>)
Codec-Unterstützung abfragen element.canPlayType(<type>)
var p = document.getElementById('player');var s = p.canPlayType("video/ogg; codecs='theora'");switch(s){ case '': alert('Sorry, no way'); break; case 'maybe': if (confirm('Own risk?')) p.play(); break; case 'probably': p.play(); break; }
Beispiel
Kochan & Partner Brand Design Development
Events
98
loadstart Der Ladevorgang wurde begonnen
loadedmetadata Die Meta-Daten der Datei wurden geladen
canplay Abspielen nun möglich
canplaythrough Abspielen nun ohne weiteres Buffering möglich
play Abspielen wurde gestartet
ended Das Medienelement hat sein Ende erreicht
document.getElementById('player').addEventListener('ended', function() { alert('Ende, aufwachen!'); });
Beispiel
Kochan & Partner Brand Design Development
Fehlerbehandlung (1)
99
element.errorelement.error
null Kein Fehler
1 MEDIA_ERR_ABORTED Abbruch durch den Benutzer
2 MEDIA_ERR_NETWORK Netzwerkfehler
3 MEDIA_ERR_DECODE Fehler beim Dekodieren
4 MEDIA_ERR_SRC_NOT_SUPPORTED Dateiformat/Codec nicht unterstützt
element.networkStateelement.networkState
0 NETWORK_EMPTY Ladevorgang noch nicht begonnen
1 NETWORK_IDLE Kein Element zu laden
2 NETWORK_LOADING Ladevorgang
3 NETWORK_LOADED Ladevorgang abgeschlossen
4 NETWORK_NO_SOURCE Keine Mediendatei vorhanden
Kochan & Partner Brand Design Development
Fehlerbehandlung (2)
100
element.readyStateelement.readyState
0 HAVE_NOTHING Noch keine Daten vorhanden
1 HAVE_METADATA Metadaten vorhanden (duration, ...)
2 HAVE_CURRENT_DATA Erste Daten liegen vor, jedoch noch nicht ausreichend, um abzuspielen
3 HAVE_FUTURE_DATADaten für aktuelle Position und die nächstenSekunden liegen vor, abspielen kann starten
4 HAVE_ENOUGH_DATAEntweder komplett geladen oder Abschätzung aufgrund aktueller Netzwerkperformance ok
Kochan & Partner Brand Design Development
And The Oscar Goes To...
101
Firefox 3.5+
Safari 4+
Chrome 3+
Opera 10.5+
IE6–8
IE9
Theora/Vorbis ü — ü ü — —
H.264/AAC — ü ü — — ü
MP3 — ü ü — — ü
WAV ü ü ü ü — —
WebM ü 4+ — ü ü 10.6+ — —
Kochan & Partner Brand Design Development
Zusammenfassung: Audio- und Video
102
Einbindung
Audio- und Video-Attribute
Multiple Quellen
Audio- und Video API: Member, Methoden und Events
Fehlerbehandlung: error, networkState, readyState
Codecs
Brand Design Development
Kochan & Partner Brand Design Development103
SemantikFormulareVideo & AudioApplication Cache
Kochan & Partner Brand Design Development
Überblick Offline-Techniken
104
Application Cache
DOM Storage
Web SQL
IndexedDB
User Data
On-/Offline-Events und -Status-Abfrage
Kochan & Partner Brand Design Development
HTML-Einbindung
105
<html manifest="cache.manifest"> <head> <title>The Works offline... </head> ...</html>
index.html
Referenzierung der Manifest-Datei im HTML-Element
Auslieferung der Datei mit dem Mime-Type: text/cache-manifest
Kochan & Partner Brand Design Development
Aufbau Cache Manifest (1)
106
CACHE MANIFEST# Comment your lines with "#"
# Cache theseindex.htmlimg/assets/band.jpgimg/assets/instruments.jpg
cache.manifest
Einleitung der zu cachenden Dateien mit CACHE MANIFEST
Auflistung jeder zu cachender Datei
Mehrere unterschiedliche Sektionen pro Cache-Datei möglich
Kochan & Partner Brand Design Development
Aufbau Cache Manifest (2)
107
CACHE MANIFEST# Comment your lines with "#"
# Cache theseindex.htmlimg/assets/band.jpgimg/assets/instruments.jpg
NETWORKonly-online.htmlimg/really-current-status.gif
cache.manifest
Festlegung von Inhalten, die nur über eine Netzwerkverbindung bezogen werden dürfen (= no cache)
Kochan & Partner Brand Design Development
Aufbau Cache Manifest (3)
108
CACHE MANIFEST# Comment your lines with "#"
# Cache theseindex.htmlimg/assets/band.jpgimg/assets/instruments.jpg
NETWORKonly-online.htmlimg/really-current-status.gif
FALLBACK/ sorry-you-are-offline.html
cache.manifest
Alternativ-Inhalte zur Ausgabe bei nicht erreichbaren Ressourcen des NETWORK-Abschnitts
Kochan & Partner Brand Design Development
Events
109
checking Manifest wird erstmalig geladen
noupdate Keine Veränderung des Manifests
downloading Manifest und Dateien werden initial heruntergeladen
progress Dateien werden heruntergeladen
cached Alle Dateien befinden sich im Cache
updateready Alle Dateien wurden aktualisiert und befinden sich nun im Cache
obsolete Cache ist ungültig (z.B. 404) und wird gelöscht
error Fehler oder Änderung während des Downloads
Kochan & Partner Brand Design Development
Zusammenfassung: Application Cache
110
HTML-Einbindung, Mime-Type
Aufbau Cache Manifest: CACHE MANIFEST, NETWORK, FALLBACK
Javascript Events zur Cache Überwachung
Brand Design Development
Kochan & Partner Brand Design Development111
Part 2CSS
Kochan & Partner Brand Design Development112
SelektorenTextflussTransformationenTransitionen, Animationen
Kochan & Partner Brand Design Development
Selektoren CSS2.1
113
Pseudo-KlassenPseudo-Klassen
:first-child Genau das erste Kind
:last-child Genau das letzte Kind
Attribut-spezifische SelektionAttribut-spezifische Selektion
element[attribute] element mit Attribut attribute
a[target="_blank"] Anchor mit Attribut target und Attributwert exakt "_blank"
div[class~="copytext"] Division mit einer mindestens der Klasse copytext (= div.copytext)
div[lang|="de"] Division mit Attribut lang matcht alle Werte, die von links mit de beginnen, z.B. lang="de", lang="de-de, de-at"...
Kochan & Partner Brand Design Development
Selektoren CSS2.1: Demo
114
Kochan & Partner Brand Design Development
Selektoren CSS3 (1)
115
Pseudo-KlassenPseudo-Klassen
:root Das root-Element des Dokuments, body
:nth-child(n) Das n-te Kind, z.B. nth-child(7), nth-child(odd)oder nth-child(even)
:nth-last-child(n) dito, umgekehrte Zählung
:first-of-type
:last-of-type
:nth-of-type(n)
:nth-last-of-type(n)
:only-child Ein Einzelkind
:empty Ein leeres Element
:enabled, :disabled Ein- oder ausgeschaltetes Element, z.B. Button
:checked Markiertes Element, z.B. Checkbox oder Radiobox
Kochan & Partner Brand Design Development
Selektoren CSS3 (2)
116
Pseudo-ElementePseudo-Elemente
:first-line Die erste Zeile des Textes
:first-letter Der erste Buchstabe des Textes
:before Generierter Inhalt vor dem Element
:after Generierter Inhalt nach dem Element
Attribut-spezifische SelektionAttribut-spezifische Selektion
div[lang^="de"] Attributwert beginnt mit "de"
div[lang$="de"] Attributwert endet mit "de"
div[lang*="de"] Attributwert beinhaltet "de"
NegationNegation
:not(<CSS 3 Selector>) Invertierung von Selektionsbedingungen
Kochan & Partner Brand Design Development
Selektoren CSS3: Demo
117
Kochan & Partner Brand Design Development
Selektoren für WebForms 2.0
118
Pseudo-ElementePseudo-Elemente
:default Default-submit Button des Formulars
:indeterminate Unbestimmte Check- und Radioboxen
:valid Gültiger Wert
:invalid Ungültiger Wert
:in-range Innerhalb des Wertebereichs
:out-of-range Außerhalb des Wertebereichs
:required Pflichtfeld
:optional Elemente ohne required und ohne Validierung
:read-only Schreibgeschützte Elemente
:read-write Elemente ohne Schreibschutz
Kochan & Partner Brand Design Development
Selektoren für WebForms 2.0: Demo
119
Kochan & Partner Brand Design Development120
SelektorenTextflussTransformationenTransitionen, Animationen
Kochan & Partner Brand Design Development
Textfluss
121
Eingebundene Block-Darstellung display: inline-block
Mehrspaltiger Textfluss column-count, column-rule, column-gap
Textkürzung text-overflow: ellipsis Hinweis! white-space: nowrap nicht vergessen
Kochan & Partner Brand Design Development
Textfluss: Demo
122
Kochan & Partner Brand Design Development123
SelektorenTextflussTransformationenTransitionen, Animationen
Kochan & Partner Brand Design Development
Transformationen
124
Koordinatensystem & Perspektive
Hardware-Beschleunigung
Kombinierbare Transformationen
• Rotation• Skalierung • Translation • Neigung• Ursprung• Matrizen-Manipulation
Kochan & Partner Brand Design Development
Transformationen: Demo (1)
125
Kochan & Partner Brand Design Development
Transformationen: Demo (2)
126
Kochan & Partner Brand Design Development
Transformationen: Demo 2D
127
Kochan & Partner Brand Design Development128
SelektorenTextflussTransformationenTransitionen, Animationen
Kochan & Partner Brand Design Development
Transitions: Übergänge zwischen Property-Werten
129
Properties all, none, <properties>
Dauer
Timing-Funktion linear, ease*, cubic-bezier
Start-Verzögerung
Kochan & Partner Brand Design Development
Transitions: Beispiele
130
transition-property: width;transition-duration: 2s;transition-timing-function: linear;transition-delay: .5s;
Vollständige Notation
transition: width 2s linear, height 1s ease-in, left .5s ease-in-out;
Kurzschreibweise und multiple Übergänge
Kochan & Partner Brand Design Development
Transitions: Demo
131
Kochan & Partner Brand Design Development
Animationen
132
Keyframe-Defintionen Start/Ende from, to oder Prozentwert 0 – 100%
Animations-Property
• Dauer
• Anzahl Wiederholungen
• Timing-Funktion
• Richtung
Kochan & Partner Brand Design Development
Animationen: Demo
133
Kochan & Partner Brand Design Development
Zusammenfassung: CSS
134
Selektoren CSS 2.1, CSS 3
Textfluss: Blocks, Mehrspaltigkeit, Textkürzung
Transformationen 2D, 3D
Übergänge mit Transitions
Keyframe Animationen
Brand Design Development
Kochan & Partner Brand Design Development135
Part 3Javascript
Kochan & Partner Brand Design Development
Was ist HTML5?
136
Semantic
Quelle: http://www.w3.org/html/logo/
Offline & Storage
DeviceRealtime &
Communication
Multimedia3D, Graphics
& EffectsPerformance &
IntegrationCSS3
Kochan & Partner Brand Design Development
Was ist HTML5?
137
Semantic
Quelle: http://www.w3.org/html/logo/
Offline & Storage
DeviceRealtime &
Communication
Multimedia3D, Graphics
& EffectsPerformance &
IntegrationCSS3
Kochan & Partner Brand Design Development
Was ist HTML5?
138
Semantic
Quelle: http://www.w3.org/html/logo/
Offline & Storage
DeviceRealtime &
Communication
Multimedia3D, Graphics
& EffectsPerformance &
IntegrationCSS3
Kochan & Partner Brand Design Development139
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
3D, Graphics and Effects140
Kochan & Partner Brand Design Development141
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Canvas
142
Umfangreiche Browser-Unterstützung (IE ab 9)
Markup mit Fallback
Breiten- und Höhen-Angabe: HTML, CSS
Context: 2D, 3D: WebGL
Transformationen: translate, rotate, scale, transform
<canvas id="c" width="600" height="220">Fallback</canvas>
Kochan & Partner Brand Design Development143
Koordinatensystem & Raster
Quelle: https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Applying_styles_and_colors
Kochan & Partner Brand Design Development
API: Setup und Zeichnen
144
// Basic setupvar canvas = document.getElementById('c');var ctx = canvas.getContext('2d');
// rectanglesctx.strokeRect(x, y, width, height);ctx.fillRect(x, y, width, height);ctx.clearRect(x, y, width, height);
// pathctx.beginPath();...ctx.stroke(); // or/and ctx.fill();
Kochan & Partner Brand Design Development
API: Setup und Zeichnen (2)
145
ctx.lineTo(x, y); ctx.moveTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle, antiClockWiseBool);
ctx.quadraticCurveTo(cX, cY, x, y);ctx.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
Quelle: http://commons.wikimedia.org/wiki/File:Bezier_grad123.svg
Ausgangspunkt Ausgangspunkt
c x,y
x,y
c1 x,y
c2 x,y
x,y
Kochan & Partner Brand Design Development
API: Grafiken
146
ctx.drawImage(HTMLimageObject, x, y);
ctx.drawImage(HTMLimageObject, x, y, width, height);
ctx.drawImage(HTMLimageObject, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
Kochan & Partner Brand Design Development
API: Füllung und Linien
147
// Füllangaben für Objektfüllung und -outlinectx.fillStyle = <Füllangabe>;ctx.strokeStyle = <Füllangabe>;
// Beispiele für Füllangabenctx.fillStyle = 'red';ctx.fillStyle = '#ff00ff';ctx.fillStyle = 'rgb(255, 127, 0)';ctx.fillStyle = 'rgba(255, 127, 0, 0.5)';
// Linienstärke, -abschluss, -verbindung, -gehrungsbegrenzungctx.lineWidth = <Zahlwert>;ctx.lineCap = <Abschluss: 'butt', 'round', 'square'>;ctx.lineJoin = <Verbindung: 'round', 'bevel', 'miter' = Gehrung>;ctx.miterLimit = <Zahlwert>;
// globale Transparenzctx.globalAlpha = 0.3;
Kochan & Partner Brand Design Development
API: Verläufe und Muster
148
var linGradient = ctx.createLinearGradient(x1, y1, x2, y2);linGradient.addColorStop(pos, color); // pos: 0.0 ... 1.0...
var radGradient = ctx.createRadialGradient(x1, y1, r1, x2, y2, r2);...
ctx.createPattern(HTMLimageObject, type)// type: 'repeat' // 'repeat-x' // 'repeat-y' // 'no-repeat'
Kochan & Partner Brand Design Development
Demo
149
Kochan & Partner Brand Design Development
Device150
Kochan & Partner Brand Design Development151
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Geolocation
152
Abfrage der geografischen Position
Erlaubnis durch den Benutzer
Einmal-Abfrage oder kontinuierliche Überwachung
Quelle je nach Endgerät: GPS, GSM-Interpolation, WLAN...
Neben Koordination
• Höhe über Normalnull
• Richtung
• Geschwindigkeit
Kochan & Partner Brand Design Development
API
153
navigator.geolocationnavigator.geolocation
Position abfragengetCurrentPosition( <callback>, <error>, <options>)
Position überwachen watchPosition(<dito>)
Überwachung beenden clearWatch(<watchId>)
[Geoposition][Geoposition]
Genauigkeit coords.accuracy
Breitengrad, Längengrad coords.latitude, .longitude
Richtung coords.heading
Geschwindigkeit coords.speed
Genauigkeit Höhe coords.altitudeAccuracy
Höhe coords.altitude
Ermittlungszeitpunkt timestamp
Kochan & Partner Brand Design Development
Optionen
154
[PositionOptions][PositionOptions]
Hohe Genauigkeit einschalten enableHighAccuracy true / false
Maximale Laufzeit für Ermittlung timeout
Maximales Alter maximumAge
var threadId;if (navigator.geolocation) { threadId = navigator.geolocation.watchPosition( update, // function callback error, // error callback {enableHighAccuracy: true} // options as JSON object );}
function update(pos) { alert(pos.coords.latitude); }function errorCallback(error) { alert(error.message);}
Beispiel
Kochan & Partner Brand Design Development
Fehlerbehandlung
155
error.codeerror.code
0 Kein Fehler
1 PERMISSION_DENIED Zugriff nicht gestattet
2 POSITION_UNAVAILABLE Position nicht verfügbar
3 TIMEOUT Ermittlung abgelaufen
error.messageerror.message
Lokalisierte Fehlermeldung zur AusgabeLokalisierte Fehlermeldung zur Ausgabe
Kochan & Partner Brand Design Development
Demo
156
Kochan & Partner Brand Design Development157
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Device Orientation
158
Abfrage der Orientierung im dreidimensionalen Raum
Konkurrierende Spezifikationen: DeviceOrientation oder MozOrientation
Quelle je nach Endgerät: Beschleunigungssensor
Kochan & Partner Brand Design Development159
X
Y
Z
Kochan & Partner Brand Design Development160
X
Y
Z
α
Kochan & Partner Brand Design Development161
X
Y
Z
β
Kochan & Partner Brand Design Development162
X
Y
Z
γ
Kochan & Partner Brand Design Development
API
163
window.DeviceOrientationEvent window.DeviceOrientationEvent
Neigung Links/Rechts –90° ... +90° deviceorientation.gamma
Neigung Vorne/Hinten –90° ... +90° deviceorientation.beta
Himmelsrichtung 0° ... 360° deviceorientation.alpha
window.OrientationEventwindow.OrientationEvent
Neigung Links/Rechts –1 ... +1 mozorientation.x
Neigung Vorne/Hinten –1 ... +1 mozorientation.y
Vertikale Beschleunigung mozorientation.z
Kochan & Partner Brand Design Development
Demo
164
Kochan & Partner Brand Design Development
Realtime & Communication165
Kochan & Partner Brand Design Development166
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Notifications
167
(Visuelle) Benachrichtigung des Users außerhalb des Browserfensters
Ausprägungen: Notification oder HtmlNotification
Darstellung Systemabhängig, z.B. Mac OS X Mountain Lion: Mitteilungszentrale
Leider derzeit exklusiv in Webkit implementiert
Kochan & Partner Brand Design Development
API
168
window.webkitNotificationswindow.webkitNotifications
Berechtigung überprüfen checkPermission()
Berechtigung einholen requestPermission(<callback>)
Benachrichtigung erzeugen createNotification()
if (window.webkitNotification.checkPermission() == 0){ var n = window.webkitNotification.createNotification( '', // icon, unused 'Hammer to fall', // title 'Here I stand or...' // body ); n.show();}
Beispiel
Kochan & Partner Brand Design Development
Demo
169
Kochan & Partner Brand Design Development170
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
WebSocket
171
Bidirektionale Kommunikation
Reduktion des HTTP-Overheads
Technische Basis: HTTP Upgradesystem, ggf. Probleme bei Proxy-Verbindungen
URL-Schema: ws:// bzw. wss://
Format derzeit Text, binäre Daten in Vorbereitung
Kochan & Partner Brand Design Development
Server-Implementierung
172
Standard LAMP tendenziell ungeeignet, da anderes Nutzungsmuster:
• kein starrer Anfrage/Antwort-Zyklus
• große Anzahl an offenen Verbindungen
Vielfältige Serverseitige Implementierungen verfügbar u.a. für Node.js, Java, Ruby, Python
Kochan & Partner Brand Design Development
API
173
Konstruktor new WebSocket(<url>)
Nachricht vom Client senden send(<message>)
Verbindung beenden close()
onopen Verbindung aufgebaut
onerror Fehler
onmessage Eingehende Nachricht des Servers
Events
Kochan & Partner Brand Design Development
Demo
174
Kochan & Partner Brand Design Development
Performance & Integration175
Kochan & Partner Brand Design Development176
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Web Worker
177
Asynchrone Berechnung
Ausgelagert in eigene Threads
Parallele Ausführung weiterer Skripte (»non blocking«)
Kein Zugriff auf DOM-Elemente: window, document, parent
Kochan & Partner Brand Design Development
API
178
[Worker][Worker]
Konstruktor new Worker(<js-file)
Nachricht senden postMessage(<text>)
Worker beenden terminate()
Kochan & Partner Brand Design Development
Genereller Ablauf
179
w = new worker('worker.js');w.postMessage(cmd);// ...// do more stuff, script is// not blocked// ...
w.onmessage = function(e){ alert(e.data); w.terminate();}
index.html
self.addEventListener( 'message', function(e) { // do the real heavy // calc stuff // ... var result = /* ... */;
postMessage(result) }, false);
worker.js
Kochan & Partner Brand Design Development
Demo
180
5 Millionen-maliges Aufsummieren einer Zufallszahl, die mit 100,1 multipliziert wurde.
Kochan & Partner Brand Design Development
Offline & Storage181
Kochan & Partner Brand Design Development182
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Web Storage
183
Bezeichnet auch als DOM Storage
Session (sessionStorage) oder Sessionübergreifend (localStorage)
Key/Value-Paare
Zugriffsbeschränkung auf »same origin«, d.h. Protokoll/Domain/Port
Speicherplatz abhängig von Browser und BenutzereinstellungDefaults pro origin: Webkit 2,5MB, Firefox 5MB, IE 10MB
Event-Überwachung
Kochan & Partner Brand Design Development
API
184
window.localStorage | window.sessionStoragewindow.localStorage | window.sessionStorage
Key/Value-Paar setzen setItem(<key>, <value>)
Value zu Key ermitteln getItem(<key>)
Key/Value-Paar löschen removeItem(<key>)
Speicher leeren clear()
Anzahl Key/Value-Paare length
Key des n-ten Paares key(<index>)
Kochan & Partner Brand Design Development
Event storage
185
event.key Key des auslösenden Speicherzugriffs
event.oldValue Bisheriger Wert
event.newValue Neuer Wert
event.url / event.uri Adresse des verändernden Dokuments
event.storageArea localStorage oder sessionStorage
Hinweis! Der Event wird nicht in dem Dokument ausgelöst, in dem der Schreibzugriff erfolgt ist, sondern nur in allen anderen...!
Kochan & Partner Brand Design Development
Demo
186
Zweites Fenster
Kochan & Partner Brand Design Development187
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Web SQL
188
Eingestellt zugunsten von Indexed DB!
Verbreitung: Chrome, Safari, Opera, Mobile Safari, Android
Relationale Datenbank
Einfaches, direktes API
Kochan & Partner Brand Design Development
Erläuterung zum Demo
189
var db;
function storeDB() {}function deleteDB(what) {}function retrieveDB() {}function setupDB() {}
window.onload = function(){ db = openDatabase( /* ... */ ); db.transaction(function(tx) { tx.executeSql( <SQL>, [<Array of parameters>], successCallback(tx, result), errorCallback(tx, result) ); });}
Kochan & Partner Brand Design Development
Demo
190
Kochan & Partner Brand Design Development191
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
Indexed DB
192
Experimentell!
Verbreitung: Chrome, Firefox, IE10, kein Mobil-Browser
Vollständiger Name: Indexed Database API
NoSQL Datenbank
Keine starre Tabellenstruktur sondern Key/Value-Paare mit Objekten
Funktioniert nicht in dem Privacy-Modus (»privates Surfen« ö.ä.)
Schemagröße pro Origin variabel, mindestens 50MB
Kochan & Partner Brand Design Development
Genereller Ablauf, Terminologie
193
(1) Datenbank öffnen
(2) Wenn nicht vorhanden: Speicherbereich objectStore (≈ Tabellen in SQL-Datenbanken) anlegen oder auf neue Version des Schemas updaten
(3) Datenbank-Operation
(1) Transaktion erzeugen, Typ festlegen: readonly, readwrite
(2) objectStore festlegen
(3) Anfrage ausführen: add(), delete(), openCursor()
(4) Den Abschluss der Operation mit Hilfe des richtigen Events (onsuccess) überwachen
(5) Ergebnisse verarbeiten
Kochan & Partner Brand Design Development
Erläuterung zum Demo
194
var db;
function storeDB() {}function deleteDB(what) {}function retrieveDB() {}
window.onload = function(){ /* ... */ request = window.indexedDB.open(); request.onerror = function(event) { /* ... */ } request.onsuccess = function(event) { db = request.result; } request.onupgradeneed = function(event) { /* setupDB */ }}
Kochan & Partner Brand Design Development
Demo
195
Kochan & Partner Brand Design Development196
CanvasGeolocationDevice OrientationNotificationsWebSocketWebWorkerWeb StorageWeb SQLIndexed DBFile API
Kochan & Partner Brand Design Development
File API
197
window.file
window.FileReader
window.FileList
window.Blob
window.requestFileSystem
window.fileEntry
derzeit nur Chrome
Kochan & Partner Brand Design Development
File Reader API
198
Konstruktor new FileReader()
Abbruch des Ladevorgangs abort()
Datei laden readAsArrayBuffer(<file>)Datei laden
readAsBinaryString(<file>)
Datei laden
readAsDataURL(<file>)
Datei laden
readAsText(<file>, <encoding>)
onload Datei fertig geladen
onloadend Abschluss des Ladevorgangs
onloadstart Ladevorgang begonnen
onprogress Fortschritt erzielt
onabort, onerrer Abbruch oder Fehler
Events
Kochan & Partner Brand Design Development
Demo: FileList
199
Kochan & Partner Brand Design Development
Demo: FileReader
200
Kochan & Partner Brand Design Development
Geschafft.
201
Canvas
Geolocation
Device Orientation
Notifications
WebSocket
WebWorker
Web Storage
Web SQL
Indexed DB
File API
Brand Design Development
Kochan & PartnerBrandDesignDevelopment
Vielen Dank!
© 2013 – Alle Rechte vorbehalten.
Kochan & Partner GmbHHirschgartenallee 2580639 MünchenTelefon +49 89 178 49 78Fax +49 89 178 [email protected]