Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Moderne Web-Apps mit HTML5 und JavaScript

Moderne Web-Apps mit HTML5 und JavaScript

Thorsten Rinne

October 28, 2013
Tweet

More Decks by Thorsten Rinne

Other Decks in Technology

Transcript

  1. THORSTEN RINNE
    Team Lead Engineering
    36 Jahre

    View full-size slide

  2. WER BIN ICH?
    • Sebastian Springer
    • https://github.com/sspringer82
    • @basti_springer

    View full-size slide

  3. Wer seid ihr?

    View full-size slide

  4. AGENDA
    • HTML5 JavaScript APIs
    • CSS3 Neuerungen
    • ECMAScript 5 Features
    • Beispielapplikation

    View full-size slide

  5. VORAUSSETZUNG

    View full-size slide

  6. https://github.com/sspringer82/chat

    View full-size slide

  7. STRUKTUR
    • HTML (Templates)
    • CSS
    • LESS/SASS Quellen
    • JavaScript (Libraries und eigener Code)
    • Tests
    • Medien wie Bilder, Fonts, Audio, Video usw.

    View full-size slide





  8. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  9. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  10. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  11. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  12. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  13. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  14. Hallo, Berlin


    Hallo, Berlin



    View full-size slide





  15. Hallo, Berlin


    Hallo, Berlin


    View full-size slide

  16. JAVASCRIPT API
    • FullScreen API
    • Forms
    • Webworkers
    • Geolocation
    • Storage
    • Offline Application

    View full-size slide

  17. FULL SCREEN
    var elem = $('#content')[0];
    if (elem.requestFullscreen) {
    elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
    elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
    elem.webkitRequestFullscreen();
    }
    go FullScreen

    View full-size slide

  18. FULL SCREEN
    if(document.cancelFullScreen) {
    document.cancelFullScreen();
    } else if(document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
    } else if(document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
    }
    cancel FullScreen

    View full-size slide

  19. FULL SCREEN
    • Bitte mit Vorsicht verwenden
    • Styling für z.B. Hintergrund:
    • -webkit-full-screen
    • -moz-full-screen

    View full-size slide

  20. PROGRESS
    var interval = setInterval(function () {
    var progress = $('progress');
    if (progress.val() < progress.attr('max')) {
    progress.val(progress.val() + 1);
    } else {
    clearInterval(interval);
    }
    }, 10);

    View full-size slide

  21. METER
    $('meter').val(100);
    Keine Progress-Bar!
    Zur Anzeige von Werten in einem bestimmten Wertebereich

    View full-size slide

  22. DATALIST


    Angela Merkel
    Gerhard Schröder
    ...

    View full-size slide

  23. OUTPUT
    $('#output').on('input', function () {
    var nr1 = parseInt($('#nr1').val());
    var nr2 = parseInt($('#nr2').val());
    $('output').val(nr1 + nr2);
    });
    Element zur Ausgabe von Berechnungen

    View full-size slide

  24. INPUT TYPES
    • Viele Aufgaben, die bisher mit JavaScript erledigt wurden,
    funktionieren jetzt mit HTML5 nativ
    • Können kaum angepasst werden

    View full-size slide

  25. INPUT TYPES
    • tel
    • search
    • url
    • email
    • date
    • month
    • week
    • time
    • number
    • range
    • color

    View full-size slide

  26. HINWEIS
    datetime und datetime-local sind deprecated!

    View full-size slide

  27. ATTRIBUTE
    • autofocus
    • placeholder
    • form
    • required
    • autocomplete
    • pattern
    • novalidate
    • formaction
    • formenctype
    • formmethod
    • formnovalidate
    • formtarget

    View full-size slide

  28. WEBWORKER
    • Workerthreads im Browser
    • Rechenintensive Prozesse auslagern
    • Zugriff auf: navigator, location, XMLHttpRequest,...
    • Kein Zugriff auf: DOM, window, document, parent

    View full-size slide

  29. WEBWORKER
    var worker = new Worker('/js/webworker.js');
    worker.onmessage = function (msg) {
    $('#result').html(msg.data);
    };

    View full-size slide

  30. WEBWORKER
    var i, n = 1, results = 1;
    outerLoop: while (true) {
    n += 1;
    for (i = 2; i <= Math.sqrt(n); i += 1) {
    if (n % i === 0) {
    continue outerLoop;
    }
    }
    self.postMessage(n);
    results += 1;
    if (results >= 1000) {
    self.close();
    }
    }

    View full-size slide

  31. WEBSOCKETS
    • Bidirektionale Kommunikation zwischen Client und Server
    • Protokoll auf TCP-Basis
    • Eventbasiert
    • Sichere Variante wss://

    View full-size slide

  32. WEBSOCKETS
    var addr = 'ws://localhost:8181/';
    var socket = new WebSocket(addr, 'myapp');
    $('#sayHello').on('click', function () {
    socket.send('Hello Server');
    });
    socket.onmessage = function (msg) {
    $('#response').html(msg.data);
    };

    View full-size slide

  33. WEBSOCKETS
    var WebSocketServer = require('websocket').server;
    var http = require('http');
    var server = http.createServer().listen(8181);
    wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
    });
    wsServer.on('request', function(req) {
    var connection = req.accept('myapp', req.origin);
    connection.on('message', function(message) {
    connection.sendUTF("Hello Client!");
    console.log(message.utf8Data);
    });
    });

    View full-size slide

  34. GEOLOCATION
    • Aktuelle Position des Clients
    • WLAN-Position
    • GPS-Position

    View full-size slide

  35. GEOLOCATION
    var geolocation = navigator.geolocation;
    geolocation.getCurrentPosition(function (pos) {
    var posString = 'Lat: ' + pos.coords.latitude +
    ' Long: ' + pos.coords.longitude;
    $('#position').html(posString);
    });

    View full-size slide

  36. function initialize() {
    navigator.geolocation.getCurrentPosition(function (pos) {
    var myLatlng = new google.maps.LatLng(pos.coords.latitude,
    pos.coords.longitude);
    var mapOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById('map-
    canvas'), mapOptions);
    var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Hello World!'
    });
    });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

    View full-size slide

  37. STORAGE
    • Local Storage - zeitlich unbegrenzt
    • Session Storage - nur für eine Browser-Session
    • IndexedDB
    • Web SQL

    View full-size slide


  38. Items in Storage:  



    keyvalue





    key:



    value:



    OK


    View full-size slide

  39. var writeLine = function (k, v) {
    var line = '' + k + '' + v +
    'delete' +
    '';
    $('#content tbody').append(line);
    writeStorageLength();
    };
    for (var i = 0; i < localStorage.length; i++) {
    k = localStorage.key(i);
    v = localStorage.getItem(k);
    writeLine(k, v);
    }

    View full-size slide

  40. var writeStorageLength = function () {
    $('#itemCount').html(localStorage.length);
    };
    $('#save').on('click', function () {
    var k = $('#storageKey').val();
    var v = $('#storageVal').val();
    localStorage.setItem(k, v);
    writeLine(k, v);
    });
    $('#content').on('click', function (e) {
    localStorage.removeItem($(e.target).data('value'));
    $(e.target).closest('tr').remove();
    writeStorageLength();
    });

    View full-size slide

  41. OFFLINE APPLICATION

    View full-size slide

  42. OFFLINE APPLICATION
    • Dateien werden nur einmalig vom Server geholt
    • Manifestdatei enthält die Konfiguration

    View full-size slide

  43. OFFLINE APPLICATION
    CACHE MANIFEST
    index.html
    js/articles.js
    js/customers.js
    js/init.js
    js/jquery.js
    js/orders.js
    css/bootstrap.css?v=1
    NETWORK:
    orders
    offline.manifest

    View full-size slide

  44. OFFLINE APPLICATION

    View full-size slide

  45. OFFLINE APPLICATION
    Creating Application Cache with manifest http://localhost:8080/offline.manifest
    Application Cache Checking event
    Application Cache Downloading event
    Application Cache Progress event (0 of 7) http://localhost:8080/js/customers.js
    Application Cache Progress event (1 of 7) http://localhost:8080/css/bootstrap.css?v=1
    Application Cache Progress event (2 of 7) http://localhost:8080/js/jquery.js
    Application Cache Progress event (3 of 7) http://localhost:8080/js/articles.js
    Application Cache Progress event (4 of 7) http://localhost:8080/index.html
    Application Cache Progress event (5 of 7) http://localhost:8080/js/init.js
    Application Cache Progress event (6 of 7) http://localhost:8080/js/orders.js
    Application Cache Progress event (7 of 7)
    Application Cache Cached event

    View full-size slide

  46. CSS LEVEL 3
    • In der Entwicklung seit 2000
    • Modularer Aufbau
    • Bekannte Module
    • Selectors Level 3
    • Media Queries

    View full-size slide

  47. BROWSER PREFIXES
    • -moz-
    • -ms- / -mso-
    • -kthml-
    • -o-
    • -webkit-
    • n/a

    View full-size slide

  48. BROWSER PREFIXES
    .round-corners {
    border-radius: 12px;
    -moz-border-radius: 12px;
    -webkit-border-radius: 12px;
    -o-border-radius: 12px;
    -khtml-border-radius: 12px;
    }

    View full-size slide

  49. Opacity
    Opacity
    Opacity
    Opacity
    Opacity

    View full-size slide

  50. OPACITY
    .my-opacity {
    opacity: 0.8;
    -ms-filter: "alpha(opacity=80)";
    filter:alpha(opacity=80);
    }

    View full-size slide

  51. GRADIENTEN
    background: linear-gradient(135deg,
    #4c4c4c 0%,#595959 12%,#666666
    25%,#474747 39%,#2c2c2c 50%,#000000
    51%,#111111 60%,#2b2b2b 76%,#1c1c1c
    91%,#131313 100%);

    View full-size slide

  52. GRADIENTEN
    filter: progid:
    DXImageTransform.Microsoft.gradient(
    startColorstr='#4c4c4c',
    endColorstr='#131313',
    GradientType=1
    );

    View full-size slide

  53. BORDER RADIUS

    View full-size slide

  54. BORDER RADIUS
    .curved {
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    -khtml-border-radius: 20px;
    border-radius: 20px;
    }

    View full-size slide

  55. BOX SHADOW
    .shadow {
    -webkit-box-shadow: 2px 2px 2px 2px
    rgba(0, 0, 0, 1);
    box-shadow: 2px 2px 2px 2px rgba(0, 0,
    0, 1);
    }

    View full-size slide

  56. MEDIA QUERIES

    View full-size slide

  57. MEDIA QUERIES
    @media (min-width: 1200px) { ... }
    @media (min-width: 768px) and (max-width:
    979px) { ... }
    @media (max-width: 767px) { ... }
    @media (max-width: 480px) { ... }

    View full-size slide

  58. SELECTORS LEVEL3
    • a[src^="https"]
    Jedes Element, dessen src-Attribut mit https beginnt
    • a[src$=".pdf"]
    Jedes Element, dessen src-Attribut mit .pdf endet
    • a[src*="jsdays"]
    Jedes Element, dessen src-Attribut mit jsdays beinhaltet

    View full-size slide

  59. SELECTORS LEVEL3
    • p:nth-child(2n)
    Jedes 2. Element seines Elternelements
    • :root
    Das Rootelement eines Dokuments
    • :empty
    Jedes Element ohne Kindelemente

    View full-size slide

  60. SELECTORS LEVEL3
    • input:enabled
    Jedes aktive Element
    • input:disabled
    Jedes nicht aktive Element
    • input:checked
    Jedes „ge-checkte“ Element (Checkbox)

    View full-size slide

  61. GRUNDLAGEN UND
    FORTGESCHRITTENE THEMEN
    • Frameworks
    • ECMAScript 5
    • Object.*
    • JSLint

    View full-size slide

  62. ECMASCRIPT 5

    View full-size slide

  63. ECMASCRIPT 5
    • http://www.ecma-international.org/publications/files/ECMA-ST/
    Ecma-262.pdf
    • JSON (parse, stringify)
    • Object.*
    • strict mode

    View full-size slide

  64. OBJECT.*
    • Erweiterbarkeit
    • Object.preventExtensions(obj)
    • Object.isExtensible(obj)

    View full-size slide

  65. OBJECT.*
    • Obj.create(proto, props)
    • Object.keys(obj)
    • Object.getOwnPropertyNames(obj)
    • Object.getOwnPropertyDescriptor(obj, prop)
    • Object.defineProperty(obj, prop, desc)

    View full-size slide

  66. OBJECT.*
    • Object.seal(obj)/Object.isSealed(obj)
    • Keine Änderungen mehr an Eigenschaften
    • Object.freeze(obj)/Object.isFrozen(obj)
    • Keine Schreibzugriffe mehr auf Eigenschaften + seal

    View full-size slide

  67. OBJECT.*
    • Object.defineProperty
    • set: magic setter function
    • get: magic getter function
    • value: default value
    • configurable: can be deleted
    • enumerable: can be iterated
    • writable: can be changed

    View full-size slide

  68. JSLINT
    JSLint will hurt your feelings

    View full-size slide

  69. JSLINT
    • „The JavaScript Quality Tool“
    • http://www.jslint.com/
    • Integriert in
    • CLI
    • IDE

    View full-size slide

  70. “USE STRICT”

    View full-size slide

  71. STRICT MODE
    MEHR FEHLER
    • Keine versehentlichen globals (ReferenceError)
    • Schärfere Regeln bei Zuweisungen
    • Non-writable, getter-only, neue Properties bei non-extensible Objekten
    • Kein Löschen von nicht löschbaren Eigenschaften (prototype)
    • Eindeutige Propertynamen
    • Eindeutige Namen für Argumente (function (a, a, b)...)
    • Keine Oktalnotation (z.B. 012 - SyntaxError)

    View full-size slide

  72. STRICT MODE
    EINFACHERE BENUTZUNG
    • “with” ist verboten
    • (var x = 1; with (obj) { x};)
    • Keine neuen Variablen mit “eval”
    • eval(“var x”);
    • Keine Variablen löschen
    • var x = 123; delete x;

    View full-size slide

  73. STRICT MODE
    EINFACHERE BENUTZUNG
    • “with” ist verboten
    • (var x = 1; with (obj) { x};)
    • Keine neuen Variablen mit “eval”
    • eval(“var x”);
    • Keine Variablen löschen
    • var x = 123; delete x;

    View full-size slide

  74. STRICT MODE
    EVAL & ARGUMENTS
    • eval und arguments können nicht mehr mit anderen Werten
    belegt oder an einen Kontext gebunden werden
    • arguments kann nicht mehr durch Aliases verändert werden
    • function func(arg) { var arg = 15; return [arg,
    arguments[0]]};
    • arguments.callee existiert nicht mehr - TypeError

    View full-size slide

  75. STRICT MODE
    SICHERHEIT
    • Kein Zugriff mehr auf das globale Objekt aus Funktionen
    • function f() { return this; } - undefined
    • Kein Zugriff auf func.arguments und func.caller von außerhalb
    • Kein Zugriff auf Variablen in einer Funktion von außerhalb

    View full-size slide

  76. STRICT MODE
    • Reservierte Wörter: implements, interface, let, package,
    private, protected, public, static, und yield
    • Keine Funktionsdefinition in Bedingungen und Schleifen

    View full-size slide

  77. REALTIME CHAT

    View full-size slide

  78. PACKAGE.JSON
    {
    "dependencies": {
    "express": ">=3.4.x",
    "jade": ">=0.35.x",
    "socket.io": ">=0.9.x"
    }
    }

    View full-size slide

  79. var express = require('express');
    var app = express();
    app.get('/', function (req, res) {
    res.send('Hello World');
    });
    app.listen(8080);

    View full-size slide

  80. AUFBAU
    HTTP-Modul
    Webserver, Request,
    Response
    Connect Middleware
    Express Routing

    View full-size slide

  81. ROUTING
    app.(url, [callback...], callback)
    function (req, res, next) {
    ...
    next();
    }
    get
    post
    put
    delete
    ...

    View full-size slide

  82. MIDDLEWARE
    app.use([path], function)
    function (req, res, next) {
    ...
    next();
    }

    View full-size slide

  83. MIDDLEWARE
    var dir = __dirname + ‘/images’
    app.use(‘/images’, express.static(dir));
    express.logger() Access Log auf der Konsole
    express.bodyParser() Zugriff auf req.body
    express.cookieParser() Cookies in Node.js
    express.cookieSession({secret:
    'mySecret'})
    Cookiebasierte Session
    req.session

    View full-size slide

  84. JADE - TEMPLATE ENGINE
    • Shortcuts - Attribute, Klassen, IDs
    • Platzhalter
    • Mixins
    • Includes
    • Extends

    View full-size slide

  85. JADE - EINBINDUNG
    app.set('views', __dirname + '/app/views');
    app.set('view engine', 'jade');

    View full-size slide

  86. SOCKET.IO
    var http = require('http');
    var server = http.createServer(app);
    server.listen(8080);
    var io = require('socket.io').listen(server);
    io.sockets.on('connection', function (socket)
    {
    socket.on('msg', function(message) {
    console.log(message);
    });
    });

    View full-size slide

  87. script(src="http://localhost:8080/
    socket.io/socket.io.js")
    var socket = io.connect('http://localhost:
    8080');
    $('#chat').on('submit', function (e) {
    e.preventDefault();
    var value = $('#message').val();
    $('#message').val('');
    $('#message').focus();
    $('#messages').append(value + '
    ');
    socket.emit('msg', value);
    return false;
    });

    View full-size slide

  88. BOWER
    • Package Manager
    • npm install -g bower

    View full-size slide

  89. BOWER
    • bower search
    • bower install [#]
    • --save -> Installation + bower.json
    • bower update
    • bower uninstall
    • bower list
    • bower lookup

    View full-size slide

  90. BOWER INSTALL
    • bower install jquery#1.7.0
    • bower install git://github.com/pivotal/jasmin.git
    • bower install http://backbonejs.org/backbone.min.js

    View full-size slide

  91. BOWER.JSON
    • name
    • version
    • dependencies
    • main
    • devdependencies
    • resolutions

    View full-size slide

  92. BOWER.JSON
    {
    "name": "Realtime Chat Application",
    "version": "0.1.0",
    "dependencies": {
    "jquery": "latest"
    }
    }

    View full-size slide

  93. GRUNT
    • npm install -g grunt-cli
    • npm install grunt
    • Plugins
    • Gruntfile.js

    View full-size slide

  94. BOOTSTRAP
    • Scaffolding (Grid, Layout, Responsive)
    • Base CSS (Buttons, Forms, Tables)
    • Components (Navigation, Alerts, Pagination)
    • JavaScript (Modal, Tooltip)

    View full-size slide

  95. BOOTSTRAP
    <br/><link rel="stylesheet"<br/>type="text/css"<br/>href="/public/css/bootstrap.min.css"><br/><link rel="stylesheet"<br/>type="text/css"<br/>href="/public/css/bootstrap-<br/>theme.min.css"><br/>

    View full-size slide

  96. BOOTSTRAP



    value="Send"
    class="btn btn-primary">


    View full-size slide

  97. LESS
    Dynamic Stylesheet Language

    View full-size slide

  98. LESS
    • Variablen
    • Nested Rules
    • Mixins

    View full-size slide

  99. LESS - VARIABLEN
    @background: #FFFFE0;
    #messages {
    background-color: @background;
    }

    View full-size slide

  100. LESS - NESTED RULES
    #head {
    background-color: @dark;
    height:25px;
    div {
    color: @light;
    background-color: @dark;
    &:hover {
    background-color: @light;
    color: @dark;
    }
    }
    }

    View full-size slide

  101. LESS - MIXINS
    .rounded-corners (@radius: 10px;) {
    -webkit-border-radius: @radius;
    -moz-border-radius: @radius;
    border-radius: @radius;
    }
    #info {
    .rounded-corners(5px);
    width: 250px;
    margin: 10px;
    padding-left: 5px;
    background-color: lightgreen;
    }

    View full-size slide

  102. DISTANZ
    geolocation

    View full-size slide

  103. HISTORY
    localstorage

    View full-size slide

  104. LITTLE HELPERS

    View full-size slide

  105. POLYFILLS
    https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-
    browser-Polyfills

    View full-size slide

  106. yepnope({
    test : Modernizr.geolocation,
    yep : 'normal.js',
    nope : ['polyfill.js', 'wrapper.js']
    });

    View full-size slide

  107. FRAMEWORKS
    • Bootstrap
    • Foundation v3
    • Foundation v4
    • Skeleton
    • 960.gs
    • http://responsive.vermilion.com/compare.php

    View full-size slide

  108. MOZILLA DEVELOPER
    NETWORK

    View full-size slide

  109. KONTAKT
    Sebastian Springer
    sebastian.springer@mayflower.de
    Mayflower GmbH
    Mannhardtstr. 6
    80538 München
    Deutschland
    @basti_springer
    https://github.com/sspringer82
    Thorsten Rinne
    [email protected]
    Yatego GmbH
    Kobellstr. 15
    80336 München
    Deutschland
    @ThorstenRinne
    https://github.com/thorsten

    View full-size slide