Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
HTML5 Open Day Lecturer: Roi Yehoshua [email protected] 05/09/2012 Agenda • HTML 5.0 Introduction • Overview of HTML5 new features • Overview of CSS3 capabilities and new features 2 © Roi Yehoshua, 2012 Introduction • HTML5 is the next generation of HTML and it will be the new standard for HTML, XHTML, and the HTML DOM. • HTML5 is still a work in progress. However, most modern browsers have some HTML5 support. • HTML5 introduces a collection of new features - rich typography, native audio & video, powerful drawing and image manipulation API – allows you to create web pages with unparalleled user experience. 3 © Roi Yehoshua, 2012 HTML Timeline 4 © Roi Yehoshua, 2012 HTML5 Goals • New features should be based on HTML, CSS, DOM, and JavaScript • Reduce the need for external plugins (like Flash or Silverlight) • Better error handling • More markup to replace scripting • HTML5 should be device independent • The development process should be visible to the 5 © Roi Yehoshua, 2012 HTML5 New Features • • • • • • • • • New structural elements Canvas <video> and <audio> tags Geolocation Form enhancements Web Storage Web SQL Web Socket Web Workers • • • • • • • • 6 Offline web applications Web GL Drag and drop FileSystem API History API Messaging API Desktop Notifications And more… © Roi Yehoshua, 2012 HTML5 Desktop Browser Support 7 © Roi Yehoshua, 2012 The Mobile Web Challenge • The mobile web is massive • 10+ billion web-enabled mobile devices by 2013 • Each mobile platform has its own programming language • • • • • • iPhone apps are written in Objective C. Android apps are written in Java. Symbian apps are written in C++. Blackberry apps are written in Java (but not the same Java as Android). WinPhone apps are written in .NET 8 © Roi Yehoshua, 2012 Mobile Web • Web technology is the one thing all devices have in common • Using HTML, CSS and JavaScript, we can write applications that will run on any device. • These apps can run online or offline using HTML5 offline capabilities • Web apps can integrate special device capabilities to create Hybrid Applications 9 © Roi Yehoshua, 2012 One codebase, all platforms 10 © Roi Yehoshua, 2012 jQuery Mobile • A unified, HTML5-based user interface system for all popular mobile device platforms • Built on the rock-solid jQuery and jQuery UI libraries • Implements native looking UI components • Latest stable version 1.1.1 (July 2012) 11 © Roi Yehoshua, 2012 Real-World jQM http://www.jqmgallery.com/ 12 © Roi Yehoshua, 2012 PhoneGap • PhoneGap is an open-source mobile development framework "connecting" solution from mobile web to native. • It enables to build applications for mobile devices using JavaScript, HTML5 and CSS3, instead of often less-known languages such as Objective-C. 13 © Roi Yehoshua, 2012 Hybrid Apps 14 © Roi Yehoshua, 2012 PhoneGap Selected Apps 15 © Roi Yehoshua, 2012 Web vs. Native Web Coding Native Write once, test everywhere Write everywhere, test everywhere Device Capabilities Use limited device capabilities Use full device capabilities Look & Feel Build your own UI components Use device UI Components Typical Use Cases Provide information about service/business M-Commerce (Mobile online shop) Simple games Photo taking app 3D or complex games 16 © Roi Yehoshua, 2012 HTML5 Editors • HTML5 Open Source Editors • Komodo Edit http://www.activestate.com/komodo-edit • Maquetta, IBM’s open source WYSIWYG HTML5 Editor http://maqetta.org/ • Many other HTML5 editors are available on the web • The Helios release of the Eclipse IDE for Java EE Developers provides support for HTML5 development. • Visual studio 2010 SP1 has a Web Standards Update that adds HTML5 and CSS3 support • http://visualstudiogallery.msdn.microsoft.com/a15c3ce9f58f-42b7-8668-53f6cdc2cd83 © Roi Yehoshua, 2012 17 The HTML5 Skeleton • DOCTYPE is always the first tag but no URL required • Required by browsers to trigger a standards mode <!DOCTYPE html> • Character encoding is optional but should be present <meta charset="utf-8" /> • This is all you need to set encoding • content and http-equiv are allowed but not required • No need to specify type attribute in <script> and <link> tags 18 © Roi Yehoshua, 2012 Basic HTML5 Page <!DOCTYPE html> <html> <head> <title>My Amazing Page</title> <meta charset="utf-8" /> <link href="style.css" rel="stylesheet" /> <script> alert("Hello there"); </script> </head> <body> This is my first HTML5 page </body> </html> 19 © Roi Yehoshua, 2012 HTML5 new structural tags • HTML5 has a series of new structural elements • To create a more semantically structured page • The main building blocks of HTML5 are: • • • • • <header> <nav> <section> <article> <footer> 20 © Roi Yehoshua, 2012 Canvas • Canvas is an API for 2D drawing • Canvas is resolution-independent bitmap, which could be used for rendering graphs, game graphics or other visual graphics on the fly • No plug in required and supported heavily now • Could become a competitor to Flash and Silverlight once the feature set and IDE designers become more adept • IE versions earlier than 9 can use third-party canvas library plugin to make it work 21 © Roi Yehoshua, 2012 Using Canvas • The <canvas> element is a container <canvas id="myCanvas" width="300" height="220“/> • Write to it by first getting a reference to the object var canvas = document.getElementById("myCanvas"); • Every canvas has a drawing context var context = canvas.getContext(“2d"); • Then use this reference to draw context.fillRect(25, 25, 150, 100); 22 © Roi Yehoshua, 2012 Drawing Rectangle example <head> <script> function drawRect() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.fillStyle = "blue"; context.fillRect(25, 25, 150, 100); } </script> </head> <body onload="drawRect();"> <canvas id="myCanvas" width="300" height="220"> Update your browser to enjoy canvas! </canvas> </body> </html> 23 © Roi Yehoshua, 2012 Drawing Paths Example function drawTriangle() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.beginPath(); context.moveTo(50, 50); context.lineTo(50, 150); context.lineTo(100, 100); context.fillStyle = “red”; context.fill(); } 24 © Roi Yehoshua, 2012 Drawing Images Example function drawImage() { var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var img = new Image(); img.src = "images/koala.jpg"; img.onload = function () { context.drawImage(img, 0, 0, 400, 360); }; } 25 © Roi Yehoshua, 2012 Canvas Image Filtering • It’s possible to paint a png or jpeg image on a canvas using drawImage • Canvas also lets JS code take the pixels from the image into an array. Using this array, we can transform the pixels and write the result to a new canvas • The operation is called filtering 26 © Roi Yehoshua, 2012 Canvas Image Filtering function filterImage() { var img = document.getElementById("sourceImage"); var width = img.width; var height = img.height; var canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; var context = canvas.getContext("2d"); context.drawImage(img, 0, 0); // Grab the pixel data from the canvas var imageData = context.getImageData(0, 0, width, height); var data = imageData.data; grayScale(imageData); context.putImageData(imageData, 0, 0); img.src = canvas.toDataURL(); } 27 © Roi Yehoshua, 2012 Canvas Image Filtering function grayScale(imageData) { var data = imageData.data; // Loop through the pixels, turning them grayscale for (var i = 0; i < data.length; i += 4) { var r = data[i]; var g = data[i + 1]; var b = data[i + 2]; var v = (3 * r + 4 * g + b) / 8; data[i] = v; data[i + 1] = v; data[i + 2] = v; } imageData.data = data; } 28 © Roi Yehoshua, 2012 Canvas Image Filtering 29 © Roi Yehoshua, 2012 Games created with Canvas • A first person shooter • http://www.benjoffe.com/code/de mos/canvascape/textures • Asteroids • http://www.kevs3d.co.uk/dev/aster oids/ • Other games • http://savedelete.com/best-html5canvas-games.html 30 © Roi Yehoshua, 2012 SVG • SVG is an alternative W3C spec for creating graphics • SVG stands for Scalable Vector Graphics and it is a language for describing 2D-graphics and graphical applications in XML. • SVG is mostly useful for vector type diagrams like Pie charts, two-dimensional graphs etc. 31 © Roi Yehoshua, 2012 Embedding SVG in HTML5 • HTML5 allows embedding SVG directly using the <!DOCTYPE html> <svg> tag <head> <title>SVG</title> <meta charset="utf-8" /> </head> <body> <h2>HTML5 SVG Circle</h2> <svg id="svgelem" xmlns="http://www.w3.org/2000/svg"> <circle id="redcircle" cx="50" cy="50" r="50" fill="red" /> </svg> </body> </html> 32 © Roi Yehoshua, 2012 Canvas vs. SVG • Vectors vs. Pixels • SVG is vector based • Canvas offers pixel operations • Document vs. Script • SVG images are defined in XML • Canvas is script-based and requires JavaScript • SVG is best suited to scalable and interactive graphics • Canvas is the best option for fast games or animations • SVG is a plug-in for IE8 or less 33 © Roi Yehoshua, 2012 HTML5 Multimedia • Multimedia support has always been a delivery issue • Commonly the <object> tag provided the support • With a classid attribute to denote the plugin required • The non-standard <embed> may also be nested for legacy browser support • Execution is then passed from the browser to a plugin • User must have a correct version of plugin 34 © Roi Yehoshua, 2012 HTML5 Video • The <video> element has a src attribute • By default shows first frame of video but does not start • Add an autoplay attribute to initialize • Add controls attribute for user control • In the same way as <object> add legacy support <video src="myvideo.mp4" autoplay controls> <p>Your browser fights the future!</p> </video> 35 © Roi Yehoshua, 2012 The Codec Issue • The HTML5 spec does not mandate a specific video format • YouTube has already moved to a HTML5 video support based on Apple’s H.264 codec • Both Firefox and Opera have refused to use H.264 because it’s heavily patented and expensive • Google have provided an open source alternative called WebM • Broad support • Not from Apple 36 © Roi Yehoshua, 2012 The Source element • Media must be supported in multiple formats • The <source> element gives multiple chances • Use instead of src attribute on video tag <video id="myVideo" width="600" height="400" controls autoplay loop> <source src="video/big_buck_bunny.mp4" /> <source src="video/big_buck_bunny.ogv" /> <source src="video/big_buck_bunny.webm" /> </video> 37 © Roi Yehoshua, 2012 Video API • <video> element can be controlled via JavaScript • Used to give a consistent cross browser feel • Or dynamic functionality function toggleVideo() { var video = document.getElementById("myVideo"); if (video.paused) video.play(); else video.pause(); } 38 © Roi Yehoshua, 2012 Video API • currentTime attribute • When read, this attribute returns the current playback position in seconds • Setting this attribute will, if possible, move the playback position to the specified time index. • Media events • • • • Loadstart Play Seeking timeupdate 39 © Roi Yehoshua, 2012 Video API Demo • http://www.w3.org/2010/05/video/mediaevents.html 40 © Roi Yehoshua, 2012 HTML5 Audio • Almost identical to the video element • source elements need to be used <audio controls autoplay> <source src="audio/bach_air.mp3" /> <source src="audio/bach_air.ogg" /> Your browser doesn't support HTML5 Audio </audio> 41 © Roi Yehoshua, 2012 Combining Canvas with Video Effects • http://www.craftymind.com/factory/html5video/CanvasVideo .html 42 © Roi Yehoshua, 2012 Local Storage • Local storage will mean the death of cookies • Problems with cookies: • Cookies are limited to 4KB of data and 20 per domain • Cookies are included in every HTTP request • Wasteful plus potential bandwidth issues • Potential security issues • What modern web apps need is: • More storage space • Client based 43 © Roi Yehoshua, 2012 Local Storage • Local storage can store up to 5MB (per site) • The storage API offers two modes: • sessionStorage – available to the window until the window is closed • localStorage – spans all windows that are open on that domain. The data will last until you want to get rid of it. • Web storage has very good browser support 44 © Roi Yehoshua, 2012 Working with Local Storage • Web storage is based on named key/value pairs • Retrieve data based upon the key • Key is a string value • Value can be any JavaScript type but is held as string • Must be parsed into correct type • Using parseInt() or similar • Local storage can be treated like an associative array • Method based or array based approach • Can be used for more complex JSON structures 45 © Roi Yehoshua, 2012 Working with Local Storage • Use setItem() method to save the key-value pair localStorage.setItem("thing", 5); // or sessionStorage.setItem("key", "value"); • Read data with getItem() parsing when necessary var x = parseInt(localStorage.getItem("thing")); • Can also use direct access on the storage object (using JavaScript expando properties) localStorage.thing = 5; var x = parseInt(localStorage.thing); 46 © Roi Yehoshua, 2012 Exploring Web Storage State • Webkit browsers have the best support for looking at what is being stored in each storage type in their web inspector 47 © Roi Yehoshua, 2012 Dealing with Complex Objects • AJAX applications often hold JSON data structures • Using a JSON serialization we can add it to local storage 48 © Roi Yehoshua, 2012 JSON and JavaScript • JSON is a subset of the object literal notation of JavaScript – Can be used in the JS language with no problems var myJSONObject = { "searchResults": [ { "productName": "Aniseed Syrup", "unitPrice": 10 }, { "productName": "Alice Mutton", "unitPrice": 39 } ] }; • Can use dot or subscript operators to access members alert(myJSONObject.searchResults[0].productName); // alerts "Aniseed Syrup" 49 © Roi Yehoshua, 2012 JSON Serialization • There are two JSON methods in JavaScript: • JSON.stringify(obj) — converts an JavaScript object to a JSON string • JSON.parse(str) — converts a JSON string back to a JavaScript object • Supported from ECMAScript5 (IE9 and above) or can use json2 library (http://www.json.org/json2.js) 50 © Roi Yehoshua, 2012 JSON Serialization localStorage.products = JSON.stringify(products); var p = JSON.parse(localStorage.products); 51 © Roi Yehoshua, 2012 Get JSON from Server $.ajax({ $.getJSON('ajax/test.json', type: 'POST', function (data) { url: url, }); dataType: 'json', data: data, success: function (data) { } }); 52 © Roi Yehoshua, 2012 Web SQL • Web SQL gives us the ability to create a real database client side • Using SQLite (http://sqlite.org) • Limited to 5Mb in size • Currently supported only by Chrome, Safari and Opera • Web SQL may be dead end in development • Mozilla and Microsoft are hesitant to implement support • An asynchronous API that uses callback functions 53 © Roi Yehoshua, 2012 Create and Open Database • If you try to open a database that doesn’t exist, the API will create it on the fly for you. You also don’t have to worry about closing databases. var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024); • Parameters: • • • • Database name Version number Text description Estimated size of database 54 © Roi Yehoshua, 2012 Execute SQL • executeSql() is used for both read and write statements, includes SQL injection projection, and provides a callback method to process the results of any queries you may have written. • All SQL statements are performed under a transaction db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)'); tx.executeSql('INSERT INTO foo (id, text) VALUES (?, ?)', [id, userValue]); }); 55 © Roi Yehoshua, 2012 Execute SQL • To select values from the table, you can use a callback to capture the results: tx.executeSql('SELECT * FROM foo', [], function (tx, results) { var len = results.rows.length, i; for (i = 0; i < len; i++) { alert(results.rows.item(i).text); } }); 56 © Roi Yehoshua, 2012 HTML5 Forms • HTML5 defines many new input types and attributes to create more meaningful fields and use less unnecessary classes and ids • HTML5 provides validation tags that need no scripting • Less files to deliver • Less chance of client validation being bypassed • The most complete part of the HTML5 spec 57 © Roi Yehoshua, 2012 New Input Elements • HTML5 adds 13 new type options • Mostly extend the <input> tags with new type values • If a browser doesn’t understand, the extension is rendered as <input type=“text”> • No requirement in the spec for how browsers present • Different browsers show different UI and error messages 58 © Roi Yehoshua, 2012 HTML5 Forms Browser Support 59 © Roi Yehoshua, 2012 New Input Elements • HTML5 adds 13 new type options • Mostly extend the <input> tags with new type values • If a browser doesn’t understand, the extension is rendered as <input type=“text”> • No requirement in the spec for how browsers present • Different browsers show different UI and error messages 60 © Roi Yehoshua, 2012 Email Input Type • Add type value of email • <input type=“email”> • What happens in the client is not consistent • Safari and Opera provides submit validation • Firefox provides client validation on blue • Safari Mobile changes the input keyboard • IE does nothing • It is an easy win for a small change 61 © Roi Yehoshua, 2012 Number Input Type • Numbers often need to be constrained by range • New number type provides this functionality <input type="number" min="1" max="20" step="2" value="5" /> • Four attributes: • • • • min – lowest value max – highest value step – what value the control enumerates by value – default value 62 © Roi Yehoshua, 2012 Number Input Type • Browser support issues • Chrome and Opera display these as ‘spinboxes’ (like numeric-up down control in Windows Forms) • No other desktop browsers support this input yet • Mobile browsers display a different virtual keyboard to assist the user 63 © Roi Yehoshua, 2012 Range Input Type • Creates a slider bar • Currently supported only by Chrome and Opera • Not even Safari Mobile name="age" type="range" min="0" max="120" value="37" • Has<input the same attributes as the number type 64 /> © Roi Yehoshua, 2012 Date Input Type <input type="date" id="dateofbirth" name="dateofbirth" /> In Chrome In Opera 65 © Roi Yehoshua, 2012 Form Validation • HTML5 defines 8 types of input validations • These are JavaScript free client validation • Browser support is currently limited • IE offers no UI implementation in any version • Firefox and Opera offers the most complete implementation • Chrome is pretty good and Safari is getting better • Some controls have silent errors, not enough UI feedback 66 © Roi Yehoshua, 2012 Required Fields • You can force a field to be mandatory on the client • This can be achieved by adding the required attribute to an input, select or textarea element • An error message will appear on submit action <input type="text" id="name" name="name" required/> 67 © Roi Yehoshua, 2012 Type Validations • Using the new HTML5 input fields, you can explicitly create inputs for things like numbers, email addresses and URLs. • Browsers can validate the input fields in these more specific fields against a built-in pattern that defines what valid entries in those types <input type="email" /> 68 © Roi Yehoshua, 2012 Pattern Validations • You can use the pattern attribute to specify your own custom regular expression. <input type="tel" id="phone" name="phone" pattern="[0-9]{2,3}-[0-9]{7}"/> 69 © Roi Yehoshua, 2012 Custom Validation Messages • You can set a custom validation message using the method element.setCustomValidity(message) function check(input) { if (!input.checkValidity()) { input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!"); } else { input.setCustomValidity(""); } } 70 © Roi Yehoshua, 2012 Custom Validations • You can use setCustomValidity() to add your own custom validations, for example when the confirm password doesn’t match the original password. function checkPasswords() { var pass = document.getElementById("password"); var confirmPass = document.getElementById("confirmPassword"); if (pass.value != confirmPass.value) confirmPass.setCustomValidity("Passwords do not match"); else confirmPass.setCustomValidity(""); } 71 © Roi Yehoshua, 2012 Styling with CSS3 <head> <style type="text/css"> input[type=text]:focus:valid, input[type=email]:focus:valid, input[type=number]:focus:in-range { outline: 2px green solid; } input[type=text]:focus:invalid, input[type=email]:focus:invalid, input[type=number]:focus:out-of-range { outline: 2px red solid; } </style> </head> <body> <form id="frm1"> <label for="email">E-mail:</label> <input type="email" id="email" name="email" /> <br /> </form> </body> 72 © Roi Yehoshua, 2012 Placeholder attribute • The placeholder attribute offers default text • Gives the user example or instruction for the field • Sometimes called a watermark • Can only be used for text fields <input type="text" id="name" name="name" placeholder="First and last name" <input type="tel" id="phone" name="phone" placeholder="xx(x)-xxxxxxx"/> 73 © Roi Yehoshua, 2012 Geolocation • Geolocation API lets you share your location with trusted web sites • The latitude and longitude are available to JavaScript on the page • Enables to provide location-aware things like finding local businesses or showing your location on a map 74 © Roi Yehoshua, 2012 Get Location • navigator.geolocation is the entry point for all location related calls • To get hold of the user’s current position use the getCurrentPosition() method navigator.geolocation.getCurrentPosition(showLocation, handleLocationError); • Location querying is asynchronous, so a callback is supplied • Mandatory success callback, optional error method 75 © Roi Yehoshua, 2012 Get Location • When user agrees, a position object is passed to the success method function showLocation(position) { var lat = position.coords.latitude; var long = position.coords.longitude; var when = position.timestamp; } • Position object has two properties • coords – list of properties about location (next slide) • timesatmp – date and time when location was calculated 76 © Roi Yehoshua, 2012 Coords object • Only latitude, longitude and accuracy are guaranteed • Depends on device whether the other are supported Property Type Description latitude double Decimal degrees longitude double Decimal degrees altitude double or null Meters above the referenced ellipsoid accuracy double Meters altitudeAccuracy double or null Meters heading double or null Degrees clockwise from true north speed double or null Meters/second 77 © Roi Yehoshua, 2012 Location Tracking • Receive notifications about location changes • Can be used for navigation apps, sport apps, and more • Use navigator.geolocation.watchPosition(success, navigation.getolocation.watchPosition() error);to start watching a user’s position • The method returns a watch id. Keep it. When tracking is no longer needed, use clearWatch() with the watch id to stop. • The callback of watchPosition will get called every time location has changed 78 © Roi Yehoshua, 2012 Google Maps API • A JavaScript API to display embedded maps in web sites • Works on both desktop and mobile devices • Free to use • Full documentation: http://code.google.com/apis/maps/do cumentation/javascript/ 79 © Roi Yehoshua, 2012 Google Maps API • Add the following JavaScript to your page: <script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script> • Assign a special empty div that will contain the map. Recommended size of the div is entire page. <div id="map" style="width:100%; height:100%"> </div> • Display the map by creating a google.maps.Map object • To initialize a Map, first create a Map options object to contain map initialization variables and pass it to the Map object 80 © Roi Yehoshua, 2012 Google Maps API var ns = google.maps; var map; function init() { var opts = { center: new ns.LatLng(0, 0), zoom: 1, mapTypeId: ns.MapTypeId.HYBRID // or ROADMAP or SATELLITE }; map = new ns.Map(document.getElementById("map"), opts); } 81 © Roi Yehoshua, 2012 Update Location on Map function updateLocation() { navigator.geolocation.getCurrentPosition(success, error); } function success(position) { var latlng = new ns.LatLng(position.coords.latitude, position.coords.longitude); map.setCenter(latlng); map.setZoom(17); } 82 © Roi Yehoshua, 2012 Markers • Markers identify points on the map. • Place markers on the map using google.maps.Marker • Markers can receive "click" events, and are often used within event listeners to bring up info windows. function drawMarker(latlng) { marker = new ns.Marker({ position: latlng, map: map, title: 'You are here!' }); } 83 © Roi Yehoshua, 2012 Markers 84 © Roi Yehoshua, 2012 Offline Applications • HTML5 introduces new methods for enabling a web site or web application to function without a network connection. • When you’re working on a mobile connection and your signal drops having some level of access is better than nothing. • Can run a completely offline app as a standalone 85 © Roi Yehoshua, 2012 Manifest File • The application cache is controlled by a plain text file with a .manifest extension • Contains a list of resources to be stored for use when there is no network connectivity. • If the user goes offline but has visited the site while online, the cached resources will be loaded so the user can still view the site in a limited form. 86 © Roi Yehoshua, 2012 Manifest File 87 © Roi Yehoshua, 2012 Manifest file • A sample manifest file CACHE MANIFEST # Offline cache v1 # html files article.html # css files assets/styles.css # js files assets/javascript.js # images assets/ico_ninja-star.gif 88 © Roi Yehoshua, 2012 Manifest file • Every page that needs to use the manifest must link to it, using the manifest attribute <!DOCTYPE html> <html manifest="/cache.manifest"> <head> <title>Offline App</title> </head> <body> </body> </html> 89 © Roi Yehoshua, 2012 Web Workers • Web Workers allow for a multi-threaded execution of JavaScript programs. • A WebWorker is a JavaScript script executed from an HTML page that runs in the background, independently of other, user-interface scripts that may also have been executed from the same HTML page. • Can be used to perform a computationally expensive task without interrupting the user interface. • Web workers are currently supported by Safari, Chrome, Operaand Mozilla Firefox • IE 10 added support for Web Workers in Platform Preview 2 90 © Roi Yehoshua, 2012 Web Workers • Web workers interact with the document via message passing. • The following code loads a JavaScript file var worker = new Worker("worker_script.js"); • To send message to the worker, use the postMessage() method of the worker object worker.postMessage("Hello World!"); 91 © Roi Yehoshua, 2012 Web Workers • The event onmessage is used to retrieve information in the worker worker.onmessage = function (event) { alert("Received message " + event.data); doSomething(); } function doSomething() { //do work worker.postMessage("Work done!"); } 92 © Roi Yehoshua, 2012 Web Workers Limitations 93 © Roi Yehoshua, 2012 Web Sockets • WebSocket is a technology providing for bidirectional, full-duplex communications channels, over a single TCP socket. • It is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. • Chrome 14, Firefox 7 and Internet Explorer 10 are currently the only browsers supporting the latest draft specification ("hybi-10") of the WebSocket protocol. 94 © Roi Yehoshua, 2012 Web Sockets • Needs a dedicated server supporting web sockets • Server-Side implementations: • Socket.IO, Jetty (Java), Ruby, Python, Perl • Client Side: Native support on iPhone. • Full Solution: Socket.IO. • socket.io also provides a lot of extra functionality over existing web sockets 95 © Roi Yehoshua, 2012 Web Sockets Client var connection = new WebSocket('ws://foo.org/wall'); connection.onopen = function () { connection.send('Ping'); }; connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; connection.onmessage = function (e) { console.log('Server: ' + e.data); }; 96 © Roi Yehoshua, 2012 CSS3 • Like HTML5, CSS3 is a living standard • No unified standard yet • W3C has split the spec into modules • Each has its own timeline • CSS3 Modules Recommendation Status • http://www.css3.info/modules/ CSS3 New Features • • • • • • • • • • Improved Selectors Border Radius Box and Text Shadow RGBA color Multiple Columns Box Resizing Gradients Transitions Transforms Media Queries CSS3 Media Queries • You can query device dimensions: /* Landscape smart phone */ @media (min-width: 321px) and (max-width: 480px) { /* style goes here */ } • You can also query device orientation: @media (orientation:portrait) { /* style goes here */ } 99 © Roi Yehoshua, 2012 CSS3 Media Queries • You can also query device pixel density 100 #header { background:url(medium-density-image.png); } @media (-webkit-device-pixel-ratio: 1.5) { /* CSS for high-density screens */ #header { background:url(high-density-image.png); } } @media (-webkit-device-pixel-ratio: 0.75) { /* CSS for low-density screens */ #header { background:url(low-density-image.png); } } CSS3 Media Queries • It is also possible to use completely different CSS files – The following example links to different CSS file dependent on the device’s pixel density <link rel="stylesheet" media="(-webkit-device-pixel-ratio: 1.5)" href="hdpi.css" /> <link rel="stylesheet" media="(-webkit-device-pixel-ratio: 1.0)" href="mdpi.css" /> <link rel="stylesheet" media="(-webkit-device-pixel-ratio: 0.75)" href="ldpi.css" /> 101 © Roi Yehoshua, 2012 Responsive Web Design • Responsive Web Design (RWD) essentially indicates that a web site is crafted to use CSS3 media queries with fluid proportion-based grids, to adapt the layout to the viewing environment, and probably also flexible images. • As a result, users across a broad range of devices and browsers will have access to a single source of content, laid out so as to be easy to read and navigate with a minimum of resizing, panning and scrolling. 102 © Roi Yehoshua, 2012 Responsive Web Design • In the following example, we are going to adapt the layout of a simple web page that contains a banner, a main content area and a side bar with 3 news items to different screen sizes and orientations • We will need to classify the page into one of the following 4 types of screens: 103 – – – – Desktop or tablet landscape mode Tablet portrait mode Smartphone landscape mode Smartphone portrait mode © Roi Yehoshua, 2012 The HTML Page (1) 104 <!DOCTYPE html> <html> <head> <title>Untitled Page</title> <meta name="viewport" content="width=device-width, initial-scale" /> <link rel="Stylesheet" href="style.css" /> </head> <body> <div id="page1"> <div id="banner"> <img src="sky.gif" /> </div> <aside id="newsContainer"> <article class="newsClass"> <header class="newsTitle"> Article1 Header </header> <div class="newsContent"> .. </div> </article> <article class="newsClass"> … </article> <article class="newsClass"> … </article> </aside> The HTML Page (2) <section id="mainContent"> <p> … </p> <p> … </p> <p> … </p> </section> </div> </body> 105 Desktop Styling /* Desktop and Tablet landscape styling */ #page1 { width: 1000px; margin: 0 auto; font-family: Verdana; } #banner img { max-width: 100%; /* adjust the image size to the page's width */ } #newsContainer { width: 30%; float: right; } #mainContent { width: 68%; } 106 Desktop Styling .newsClass { border: 1px solid black; margin: 5px; } .newsTitle { background-color: #CCC; font-weight: bold; padding: 5px; } .newsContent { padding: 5px; } 107 108 Tablet Styling /* Tablet portrait styling */ @media (min-width: 480px) and (max-width: 768px) { #page1 { width: 720px; } } 109 110 Smartphone Landscape Styling /* Smartphone landscape styling */ @media (min-width: 320px) and (max-width: 480px) { #page1 { width: 440px; } #newsContainer { width: 100%; } .newsContent { display: none; } .newsClass { float: left; width: 30%; } #mainContent { width: 100%; } 111 } Smartphone Landscape Styling 112 Smartphone Portrait Styling /* Smartphone portrait styling */ @media (max-width: 320px) { #page1 { width: 280px; } #newsContainer { width: 100%; } .newsContent { display: none; } .newsClass { float: left; width: 28%; margin: 2px; } #mainContent { width: 100%; } 113} Smartphone Portrait Styling 114 © Roi Yehoshua, 2012 Thank You! • Follow me on Facebook to get news and updates on Mobile Application Development • http://www.facebook.com/RoiYehoshuaMobile App Roi Yehoshua [email protected] 115 © Roi Yehoshua, 2012