Thorsten Rinne / Sebastian Springer

Webapplikationen reloaded mit
node.js und HTML5 - Die Grundlagen
Thorsten Rinne
• 34 Jahre
• Mayflower GmbH, München
 – Senior Developer / Team Lead
 – Head of Open Source Labs
• Diplom-Informatiker (FH)
• Twitter: @ThorstenRinne
Sebastian Springer
• 29 Jahre
• Mayflower GmbH
 – Senior Developer / Team Lead
• Diplom-Informatiker (FH)
• Twitter: @basti_springer
Wer seid ihr?
Wir sprechen nicht über
 <video> und <audio>
Und wir sprechen nicht über ...
Flash ist tot.
Spätestens in 5 Jahren.

  (sagt sogar Adobe)
Wer nutzt bereits...
und wer bereits...
HTML5 in einem
   Satz?
„HTML5 is about moving from
documents to applications and
  from hacks to solutions.“



                 Chris Heilmann auf Twitter
Was bedeutet HTML5 für
     Entwickler?
HTML5 ~= HTML + CSS + JS
1989
HTML wird am CERN
    entwickelt.
1993
Die IETF verlangt die erste
Implementierung: Mosaic
1996
Tim Berners-Lee gründet das World
   Wide Web Consortium (W3C)
1996Browserkrieg:
Netscape vs. Microsoft
- Der Browser ist kostenlos   - „kostenlos“ mit OS
- Das Web ersetzt das OS      - 1995: 6 Entwickler
- Java bringt Web Apps        - 1999: 1000 Entwickler
- 4 Versionen in 7 Jahren     - 6 Versionen in 6 Jahren



           Netscape verlor den „Krieg“ ...
The dark age of the Web...
XHTML 2.0
#sadpanda
1999
PHP 3.0 - MySQL 3.22
    Apache 1.3
1999
XMLHttpRequest Object
Die Zeit verging ...
seit Version 5.0
(1999)

      seit Version 1.0
      (2004)

             seit Version 1.2
             (2004)

                    seit Version 7.6
                    (2004)
2005
Ajax: A New Approach to Web
         Applications

           Blogposting von Jesse James Garret
Google Suggest


 Google Mail


 Google Maps
2006
 Comet
Push   Ajax




              Push
Was passiert hier?
Content
  vs.
Context
Facebook ist eine
  Applikation!
Page
  vs.
Stream
Twitter ist eine
 Applikation!
Applikationen?
Apps!
online === offline
Ist das das neue Web?
Die Zukunft besteht
  aus Web Apps!
Der mobile Browser ist (fast)
 identisch mit dem Desktop
          Browser.
Der Mobile Browser hat kurze
Release-Zyklen. Der auf dem
 Desktop inzwischen auch.
Der Browser ist eine
  „cross platform
 realtime runtime“.
Was hat das nun mit
 HTML5 zu tun?
Requests

 Events
2000: PHP chat style polling




  Client              Server
2000: PHP chat style polling


     Hey, wazzup?




  Client              Server
2000: PHP chat style polling


     Hey, wazzup?   Um, nothing actually...




  Client                             Server
2000: PHP chat style polling


     Hey, wazzup?           Um, nothing actually...




  Client            1 sec                    Server
2000: PHP chat style polling




  Client              Server
2000: PHP chat style polling


     Hey, wazzup?




  Client              Server
2000: PHP chat style polling


     Hey, wazzup?   Um, nothing actually...




  Client                             Server
2000: PHP chat style polling


     Hey, wazzup?           Um, nothing actually...




  Client            1 sec                    Server
2000: PHP chat style polling




  Client              Server
2000: PHP chat style polling


     Hey, wazzup?




  Client              Server
2000: PHP chat style polling


     Hey, wazzup?   Um, nothing actually...




  Client                             Server
2000: PHP chat style polling


     Hey, wazzup?           Um, nothing actually...




  Client            1 sec                    Server
2000: PHP chat style polling

              WTF???




  Client               Server
1 user = 1 req / sec
    CPU #FAIL
2006: Comet style long poll




  Client              Server
2006: Comet style long poll


     Hey, wazzup?




  Client              Server
2006: Comet style long poll


                   Um, nothing actually...




  Client   1 sec                Server
2006: Comet style long poll


                   Well ...




  Client   1 sec         Server
2006: Comet style long poll


                   Wait ...




  Client   1 sec         Server
2006: Comet style long poll

                   Uh, there is something!




  Client   1 sec                Server
2006: Comet style long poll


                   No, nothing!




  Client   1 sec           Server
2006: Comet style long poll

           WTF???




  Client              Server
1 user = 1 apache child
   MEMORY #FAIL
Wir haben ein Problem
Wir brauchen Hilfe!
MEMORY: WIN
CPU: 1/2 WIN
PHP
                       Server
Client




     Client




              Client
Was ist node.js?
Serverseitiges JS mit V8
Eventgetriebene
  Architektur
Asynchron
Bingo!
  http://arcweb.archives.gov/arc/action/ExternalIdSearch?id=558191
Warum node.js?
Es ist schnell.
Nonblocking I/O
durch Eventloop
♥ Community Love ♥
Schnelle,
leichtgewichtige
  Entwicklung
Events
 File System
                              Streams

     Viele eingebaute
OS     Bibliotheken
            Query String
                              Debugger
     HTTP
                    URL
Heile Welt?
node.js hat auch
     seine
Schattenseiten.
Single Process
Statische Inhalte
Sehr
betriebssystemnah ...
#sadpanda #nodejs
node.js muss auch rechnen
We ♥ node.js!
Kenne die Schwächen
 deiner Infrastruktur!
Modi
Interaktiv
Nicht interaktiv



$ node server.js
Non-Blocking
Non Blocking
sleep(10);
echo ‘Hello, World‘;

                 vs.

setTimeout(
 console.log(‘Hello, World‘, 10000)
 )
$sql    = ‘SELECT * FROM users‘;
$result = $conn->query($sql);

                 vs.

var query = ‘SELECT * FROM users‘;
db.query(query,
   function(err, results, fields)
     {...};
);
Webserver
Webserver Code
var http = require(‘http‘);
http.createServer(
  function(req, res) {
    res.writeHead(
       200,
       {‘Content-Type‘: ‘text/plain‘}
    );
    res.end(‘Hello, World‘);
  }).listen(1337, ‘127.0.0.1‘);
Bibliotheken als NPM
• Socket.IO
• Backbone.js
• Underscore.js
• express
• Common.js
• MySQL, redis, CouchDB
Kleine Helfer für node.js
• Nodemon
 – https://github.com/remy/nodemon
• Forever
 – https://github.com/indexzero/forever
• Mehr?
Und was ist mit dem Client?
WebSockets
if ("WebSocket" in window) {
  var ws = new WebSocket("ws://example.com/service");
  ws.onopen = function() {
     // WebSocket is connected.
     // You can send data by send() method.
     ws.send("message to send");
   // ....
  };
  ws.onmessage = function (evt) {
     var received_msg = evt.data;
  };
  ws.onclose = function() {
     // WebSocket is closed
  };
} else {
  // the browser doesn't support WebSockets.
}
Client

GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5
Sec-WebSocket-Key2: 12998 5 Y3 1 .P00

^n:ds[4U
                                                        Server

                   HTTP/1.1 101 WebSocket Protocol Handshake
                   Upgrade: WebSocket
                   Connection: Upgrade
                   Sec-WebSocket-Origin: http://example.com
                   Sec-WebSocket-Location: ws://example.com/demo
                   Sec-WebSocket-Protocol: sample

                   8jKS'y:G*Co,Wxa-
Immer mehr Logik
wandert in den Client.
 Weg vom Backend.
WebWorker                  main.js

var myWorker = new Worker('backgroundtask.js');

  myWorker.onmessage = function(event) {
     alert(event.data);
  };



                                     backgroundtask.js

  self.onmessage = function(event) {
    // Do some heavy work
    self.postMessage('Hello, Amsterdam');
  }
Demo
MVC mit Backbone.js
                 User
       DOM                URL



    View                 Router
    Read/Write


                 Model




       Server (z.B. DB)
WebMessaging
<form>
<input type="text" name="msg" value="My message" id="msg">
<input type="submit">
<h2>Ziel iFrame:</h2>
<iframe id="iframe" src="postmessage.html"></iframe>
</form>
<script>
  var win = document.getElementById("iframe").contentWindow;
  addEvent(
    document.getElementsByTagName('form')[0], 'submit',
      function (e) {
         if (e.preventDefault)
           e.preventDefault();
         win.postMessage(document.getElementById("msg").value,
           "http://www.phpconference.nl");
         e.returnValue = false;
         return false;
  });
  </script>
Geolocation
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
      var lat     = position.coords.latitude;
      var lng     = position.coords.longitude;
      var options = {
        position: new google.maps.LatLng(lat, lng) }
      var marker = new google.maps.Marker(options);

          marker.setMap(map);
    });
}
Web Storage
‣„kurzlebige“ Daten
 ‣sessionStorage Object
 ‣wird beim Schließen des Browsers gelöscht
‣„langlebige“ Daten
 ‣localStorage Objekt
 ‣wird nicht beim Schließen des Browsers gelöscht
‣produziert File I/O, läuft synchron
 Safari/Chrome     Firefox       IE      Opera

     2 MB        5 MB ~ 200MB   5 MB      4 MB
Web Storage
 <p>This page was requested <b>
 <script>
 if (!sessionStorage.pageCounter) {
   sessionStorage.setItem('pageCounter',0);
 }

  sessionStorage.setItem('pageCounter',
    parseInt(sessionStorage.pageCounter)+1);

  document.write(sessionStorage.pageCounter);
  </script>
  </b> times.</p>
  <p>
  <input value="sessionStorage leeren" type="button"
onClick="sessionStorage.clear();location.reload(true);">
  <input value="Seite laden" type="button"
onClick="location.reload(true);">
  </p>
Demo
HTML 5
Basics
<!DOCTYPE html>
Von HTML4 nach HTML5


          KISS
Keep it simple & stupid
Von HTML4 nach HTML5


Redundante und
kaputte Elemente
 werden entfernt.
Von HTML4 nach HTML5


 HTML5 verlangt
explizit nach CSS.
<meta <meta http-
       charset=“UTF-8“>
 equiv=“Content-Type“
 content=“text/html;
   charset=UTF-8“>
<a>
          ist flexibler
       <a>, <area>
erhalten ein media Attribut
<a href=“http://
  m.twitter.com“
  rel=“alternate“
 media=“handheld“>
Twitter Mobile</a>
data Attribut

für eigene data-* Attribute
Beispiel Facebook Like


 <div class="fb-like"
data-send="true" data-
width="450" data-show-
 faces="true"></div>
<section> Bereiche
<address> und Überschriften
<header>
<hgroup>
  <nav>
<article>
<footer>
<time>
 <details>
  <figure>
<figcaption>
   <mark>
<link rel="alternate" type="application/atom+xml"
      title="My Weblog feed"
      href="http://www.phpconference.de/feed/">
<link rel="search" type="application/opensearchdescription+xml"
      title="My Weblog search"
      href="http://www.phpconference.de/opensearch.xml">
<link rel="icon" href="/favicon.ico">

<link   rel="pingback" href="http://www.phpconference.de/xmlrpc.php">
<link   rel="prefetch" href="http://www.phpconference.de/main.php">
<link   rel="archives" href="http://www.phpconference.de/archive/">
<link   rel="external" href="http://www.php.net">
<link   rel="license" href="http://www.gnu.org/licenses/gpl.html">
<link   rel="nofollow" href="http://www.ruby-lang.org">
<svg>
  Vektorgrafiken in XML

        <canvas>
Pixelgrafiken in JavaScript
Demo
HTML 5 Microdata is machine-
    readable data in HTML.
         Recursion. :-)

<div itemscope>
    <p>
    Mein Name ist <span itemprop="name">Thorsten</span>.
    </p>
</div>
WebForms
<input type="text" placeholder="Mayflower GmbH">
<input type="text" maxlength="256" name="q" autofocus>




<input type="text" maxlength="256" name="q" required="required">
<input type="tel" name="phonenumber">




<input type="url" name="url">




<input type="email" name="emailaddress">
<input type="number" min="0" max="10" step="2" value="6" />
<input type="range" min="0" max="10" step="2" value="6">
<input type="text" x-webit-speech>
<input   type="date">
<input   type="month">
<input   type="week">
<input   type="time">
<input   type="datetime">
<input type="color">
Demo
CSS3
.row:nth-child(even) { background: #cccccc; }
.row:nth-child(odd) { background: #ffffff; }




 row 1
 row 2
 row 3
 row 4
@font-face {
  font-family: 'Papyrus';
  src: url(Papyrus.otf);
}

header {
  font-family: 'Papyrus';
}




          Hallo, Welt!
Mehr CSS3 Features...
Lorem ipsum dolor       Lorem ipsum dolor       Lorem ipsum dolor       Lorem ipsum dolor
sit amet,               sit amet,               sit amet,               sit amet,
consectetur             consectetur             consectetur             consectetur
adipisicing elit, sed   adipisicing elit, sed   adipisicing elit, sed   adipisicing elit, sed
do eiusmod              do eiusmod              do eiusmod              do eiusmod
tempor incididunt       tempor incididunt       tempor incididunt       tempor incididunt
ut labore et dolore     ut labore et dolore     ut labore et dolore     ut labore et dolore
magna aliqua. Ut        magna aliqua. Ut        magna aliqua. Ut        magna aliqua. Ut
enim ad minim           enim ad minim           enim ad minim           enim ad minim
veniam, quis            veniam, quis            veniam, quis            veniam, quis
nostrud                 nostrud                 nostrud                 nostrud


    Multi-column layouts
exercitation            exercitation            exercitation            exercitation
ullamco laboris nisi    ullamco laboris nisi    ullamco laboris nisi    ullamco laboris nisi
ut aliquip ex ea        ut aliquip ex ea        ut aliquip ex ea        ut aliquip ex ea
commodo                 commodo                 commodo                 commodo
consequat. Duis         consequat. Duis         consequat. Duis         consequat. Duis
aute irure dolor in     aute irure dolor in     aute irure dolor in     aute irure dolor in
reprehenderit in        reprehenderit in        reprehenderit in        reprehenderit in
voluptate velit         voluptate velit         voluptate velit         voluptate velit
esse cillum dolore      esse cillum dolore      esse cillum dolore      esse cillum dolore
eu fugiat nulla         eu fugiat nulla         eu fugiat nulla         eu fugiat nulla
pariatur. Excepteur     pariatur. Excepteur     pariatur. Excepteur     pariatur. Excepteur
sint occaecat           sint occaecat           sint occaecat           sint occaecat
cupidatat non           cupidatat non           cupidatat non           cupidatat non
proident, sunt in       proident, sunt in       proident, sunt in       proident, sunt in
culpa qui officia       culpa qui officia       culpa qui officia       culpa qui officia
Opacity
Opacity
Opacity
Opacity
Opacity
HSL / HSLA Farben
Endlich runde Ecken! :-)
Gradienten
Shadows
Shadows
Transitions und Animations
Browser
Support :-)
79 %


                                    69 %         69 %

          64 %         64 %




30 %




IE9    Mobile Safari Safari 5.1
                                  Firefox 10
                                               Opera 11.6
                                                            Chrome 17
Was uns 2012 noch erwartet...
• Internet Explorer 10 mit Windows 8
  (64% HTML5 Support)
• Safari 5.2
  (74% HTML5 Support)
• Opera 12
  (72% HTML5 Support)
• viele neue Chrome- und Firefox-Versionen
• Chrome on Android im TV
• evtl. Mobile Safari im TV
Kleine Helfer
 für HTML5
caniuse.com
html5test.com
Kleine Helfer
  für CSS
Fragen?
Danke!
http://joind.in/4692
Kontakt

Thorsten Rinne                Sebastian Springer
thorsten.rinne@mayflower.de   sebastian.springer@mayflower.de
+49 89 242054-1131            +49 89 242054-1120

Mayflower GmbH                Mayflower GmbH
Mannhardtstr. 6               Mannhardtstr. 6
80538 München                 80538 München
Deutschland                   Deutschland

@ThorstenRinne                @basti_springer

HTML5 und node.js Grundlagen