两只小蚂蚁

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

温故而知新,画了一个思维导图

 

HTML5

  HTML5 is the fifth revision and newest version of the HTML standard. It offers new features that provide not only rich media support but also enhance support for creating web applications that can interact with users, their local data, and servers more easily and effectively than was previously possible. 

  Many new syntactic features are included. To natively include and handle multimedia and graphical content, the new <video>, <audio> and <canvas> elements were added, and support for scalable vector graphics (SVG) content and MathML for mathematical formulas. To enrich the semantic content of documents, new page structure elements such as <main>, <section>, <article>, <header>, <footer>, <aside>, <nav> and <figure>, are added. New attributes are introduced, some elements and attributes have been removed, and others such as <a>, <cite> and <menu> have been changed, redefined or standardized.

1. Semantic  

1.1 New Elements in HTML5

  Below is a list of the new HTML5 elements, and a description of what they are used for.


1.2 New Semantic/Structural Elements

  HTML5 offers new elements for better document structure:

TagDescription
<article> Defines an article in the document
<aside> Defines content aside from the page content
<bdi> Defines a part of text that might be formatted in a different direction from other text
<details> Defines additional details that the user can view or hide
<dialog> Defines a dialog box or window
<figcaption> Defines a caption for a <figure> element
<figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.
<footer> Defines a footer for the document or a section
<header> Defines a header for the document or a section
<main> Defines the main content of a document
<mark> Defines marked or highlighted text
<menuitem>  Defines a command/menu item that the user can invoke from a popup menu
<meter> Defines a scalar measurement within a known range (a gauge)
<nav> Defines navigation links in the document
<progress> Defines the progress of a task
<rp> Defines what to show in browsers that do not support ruby annotations
<rt> Defines an explanation/pronunciation of characters (for East Asian typography)
<ruby> Defines a ruby annotation (for East Asian typography)
<section> Defines a section in the document
<summary> Defines a visible heading for a <details> element
<time> Defines a date/time
<wbr> Defines a possible line-break

 


1.3 New Form Elements

TagDescription
<datalist> Defines pre-defined options for input controls
<keygen> Defines a key-pair generator field (for forms)
<output> Defines the result of a calculation

 


1.4 New Input Types

New Input TypesNew Input Attributes
  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week
  • autocomplete
  • autofocus
  • form
  • formaction
  • formenctype
  • formmethod
  • formnovalidate
  • formtarget
  • height and width
  • list
  • min and max
  • multiple
  • pattern (regexp)
  • placeholder
  • required
  • step

 


1.5 New Attribute Syntax

  HTML5 allows four different syntaxes for attributes.

  This example demonstrates the different syntaxes used in an <input> tag:

TypeExample
Empty <input type="text" value="John" disabled>
Unquoted <input type="text" value=John>
Double-quoted <input type="text" value="John Doe">
Single-quoted <input type="text" value='John Doe'>

In HTML5, all four syntaxes may be used, depending on what is needed for the attribute.


1.6 Graphics

TagDescription
<canvas> Defines graphic drawing using JavaScript
<svg> Defines graphic drawing using SVG

 


1.7 New Media Elements

TagDescription
<audio> Defines sound or music content
<embed> Defines containers for external applications (like plug-ins)
<source> Defines sources for <video> and <audio>
<track> Defines tracks for <video> and <audio>
<video> Defines video or movie content

2. OFFLINE & STORAGE

  Allowing webpages to store data on the client-side locally and operate offline more efficiently.

2.1 Offline resources: The application cache

  Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level. 

  As this solustion have a lot of potential defects, its highly recommend to deprecated.

  Deprecated:
  This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.  

2.2 Web Storage (LocalStorage & SessionStorage)

  Web storage offers two different storage areas—local storage and session storage—which differ in scope and lifetime. Data placed in local storage is per origin (the combination of protocol, hostname, and port number as defined in the same-origin policy) (the data is available to all scripts loaded from pages from the same origin that previously stored the data) and persists after the browser is closed. Session storage is per-origin-per-window-or-tab and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.

SessionStorage:

// Store value on browser for duration of the session
sessionStorage.setItem('key', 'value');

// Retrieve value (gets deleted when browser is closed and re-opened) ...
alert(sessionStorage.getItem('key'));

Local Storage:

// Store value on the browser beyond the duration of the session
localStorage.setItem('key', 'value');

// Retrieve value (persists even after closing and re-opening the browser)
alert(localStorage.getItem('key'));

Storage size:

  Web storage provides far greater storage capacity (5 MB per origin in Mozilla Firefox,and Opera; 10MB per origin in Google Chrome,10 MB per storage area in Internet Explorer; 25MB per origin on BlackBerry 10 devices) compared to 4 kB (around 1000 times less space) available to cookies.

 

 

2.3 IndexedDB

  The Indexed Database API, or IndexedDB (formerly WebSimpleDB), is a World Wide Web Consortium (W3C) recommended[1] web browser standard interface for a transactional local database of JSON objects collections with indices. Websites can collect and save permanent (more) data in a database.

  IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.

  For different Browsers, we can define as below.

        window.indexedDB = window.indexedDB ||
                           window.mozIndexedDB ||
                           window.webkitIndexedDB ||
                           window.msIndexedDB;

        window.IDBTransaction = window.IDBTransaction ||
                           window.webkitIDBTransaction ||
                           window.msIDBTransaction;

        window.IDBKeyRange = window.IDBKeyRange ||
                           window.webkitIDBKeyRange ||
                           window.msIDBKeyRange;

Example:

  In the following example, the API is used to access a "library" database that holds books stored by their "isbn" attribute. Additionally, an index is maintained on the "title" attribute of the objects stored in the object store. This index can be used to look up books by title, and enforces a uniqueness constraint. Another index is maintained on the "author" attribute of the objects, and can be used to look up books by author.

A connection to the database is opened. If the "library" database did not already exist, it is created and an event handler creates the object store and indexes. Finally, the opened connection is saved for use in subsequent examples.

var request = indexedDB.open("library");

request.onupgradeneeded = function() {
  // The database did not previously exist, so create object stores and indexes.
  var db = request.result;
  var store = db.createObjectStore("books", {keyPath: "isbn"});
  var titleIndex = store.createIndex("by_title", "title", {unique: true});
  var authorIndex = store.createIndex("by_author", "author");

  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});
};

request.onsuccess = function() {
  db = request.result;
};
//The following example populates the database using a transaction.

var tx = db.transaction("books", "readwrite");
var store = tx.objectStore("books");

store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});

tx.oncomplete = function() {
  // All requests have succeeded and the transaction has committed.
};
//The following example looks up a single book in the database by title using an index.

var tx = db.transaction("books", "readonly");
var store = tx.objectStore("books");
var index = store.index("by_title");

var request = index.get("Bedrock Nights");
request.onsuccess = function() {
  var matching = request.result;
  if (matching !== undefined) {
    // A match was found.
    report(matching.isbn, matching.title, matching.author);
  } else {
    // No match was found.
    report(null);
  }
};
//The following example looks up all books in the database by author using an index and a cursor.

var tx = db.transaction("books", "readonly");
var store = tx.objectStore("books");
var index = store.index("by_author");

var request = index.openCursor(IDBKeyRange.only("Fred"));
request.onsuccess = function() {
  var cursor = request.result;
  if (cursor) {
    // Called for each matching record.
    report(cursor.value.isbn, cursor.value.title, cursor.value.author);
    cursor.continue();
  } else {
    // No more matching records.
    report(null);
  }
};
//The following example shows how errors could be handled when a request fails.

var tx = db.transaction("books", "readwrite");
var store = tx.objectStore("books");
var request = store.put({title: "Water Buffaloes", author: "Slate", isbn: 987654});
request.onerror = function(event) {
  // The uniqueness constraint of the "by_title" index failed.
  report(request.error);
  // Could call event.preventDefault() to prevent the transaction from aborting.
};
tx.onabort = function() {
  // Otherwise the transaction will automatically abort due the failed request.
  report(tx.error);
};
//The database connection can be closed when it is no longer needed.

db.close();

Simple One:

db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) 
{
  alert("Name for SSN 444-44-4444 is " + event.target.result.name);
};

 

 

2.4 File API

  HTML5 finally provides a standard way to interact with local files, via the File API specification. As example of its capabilities, the File API could be used to create a thumbnail preview of images as they're being sent to the server, or allow an app to save a file reference while the user is offline. Additionally, you could use client-side logic to verify an upload's mimetype matches its file extension or restrict the size of an upload.

  The spec provides several interfaces for accessing files from a 'local' filesystem:

  •  File - an individual file; provides readonly information such as name, file size, mimetype, and a reference to the file handle.
  •  FileList - an array-like sequence of File objects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
  •  Blob - Allows for slicing a file into byte ranges.

  When used in conjunction with the above data structures, the FileReader interface can be used to asynchronously read a file through familiar JavaScript event handling. Thus, it is possible to monitor the progress of a read, catch errors, and determine when a load is complete. In many ways the APIs resemble XMLHttpRequest's event model.  

Reading files

  FileReader includes four options for reading a file, asynchronously:

  •  FileReader.readAsBinaryString(Blob|File) - The result property will contain the file/blob's data as a binary string. Every byte is represented by an integer in the range [0..255].
  •  FileReader.readAsText(Blob|File, opt_encoding) - The result property will contain the file/blob's data as a text string. By default the string is decoded as 'UTF-8'. Use the optional encoding parameter can specify a different format.
  •  FileReader.readAsDataURL(Blob|File) - The result property will contain the file/blob's data encoded as a data URL.
  •  FileReader.readAsArrayBuffer(Blob|File) - The result property will contain the file/blob's data as an ArrayBuffer object

3. DEVICE ACCESS

Using the Camera API

  Allows using, manipulating, and storing an image from the computer's camera.

Touch events

  Handlers to react to events created by a user pressing touch screens.

Using geolocation

  Let browsers locate the position of the user using geolocation.

Detecting device orientation

  Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).

Pointer Lock API

  Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.

 

4. CONNECTIVITY

  SSE & Web Socket, please find another blog here.

5. MULTIMEDIA

5.1 Audio

<audio controls>
  <source src="viper.mp3" type="audio/mp3">
  <source src="viper.ogg" type="audio/ogg">
  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
</audio>

A simple, typical workflow for web audio would look something like this:

  1. Create audio context
  2. Inside the context, create sources — such as <audio>, oscillator, stream
  3. Create effects nodes, such as reverb, biquad filter, panner, compressor
  4. Choose final destination of audio, for example your system speakers
  5. Connect the sources up to the effects, and the effects to the destination.

A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information.

Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.

Example:

 

var context = new AudioContext();

function playSound() {
    var source = context.createBufferSource();
    source.buffer = dogBarkingBuffer;
    source.connect(context.destination);
    source.start(0);
}

  

5.2 Video

  The <video> element contains one or more video sources. To specify a video source, use either the src attribute or the <source> element; the browser will choose the most suitable one. For a list of supported formats, see Media formats supported by the audio and video elements.

<video poster="movie.jpg" controls>
    <source src="movie.webm" type='video/webm; codecs="vp8.0, vorbis"'>
    <source src="movie.ogv" type='video/ogg; codecs="theora, vorbis"'>
    <source src="movie.mp4" type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
    <p>This is fallback content to display for user agents that do not support the video tag.</p>
</video>

 

6. (3D), Graphics & Effects

6.1 SVG

  SVG is an XML language, similar to XHTML, which can be used to draw vector graphics, such as the ones shown to the right. It can be used to create an image either by specifying all the lines and shapes necessary, by modifying already existing raster images, or by a combination of both. The image and its components can also be transformed, composited together, or filtered to change their appearance completely.

<svg width="300" height="200">
  <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"/>
Sorry, your browser does not support inline SVG.
</svg>

  

 

 6.2 Canvas

  The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. 

  Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

  

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <script type="application/javascript">
    function draw() {
      var canvas = document.getElementById('canvas');
      if (canvas.getContext) {
        var ctx = canvas.getContext('2d');

        ctx.fillStyle = 'rgb(200, 0, 0)';
        ctx.fillRect(10, 10, 50, 50);

        ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
        ctx.fillRect(30, 30, 50, 50);
      }
    }
  </script>
 </head>
 <body onload="draw();">
   <canvas id="canvas" width="150" height="150"></canvas>
 </body>
</html>

  

 

6.3 Differences Between SVG and Canvas

  SVG is a language for describing 2D graphics in XML.

  Canvas draws 2D graphics, on the fly (with a JavaScript).

  SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.

  In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

  Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.


6.4 Comparison of Canvas and SVG

  The table below shows some important differences between Canvas and SVG:

CanvasSVG
  • Resolution dependent
  • No support for event handlers
  • Poor text rendering capabilities
  • You can save the resulting image as .png or .jpg
  • Well suited for graphic-intensive games
  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game applications

 

6.5 WebGL

  WebGL(Web Graphics Library) enables web content to use an API based on OpenGL ES 2.0 to perform 2D and 3D rendering in an HTML canvas in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and shader code (GLSL) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.

  

// Get A WebGL context
var canvas = document.getElementById("canvas");
var gl = canvas.getContext("experimental-webgl");

// setup a GLSL program
var program = createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);
gl.useProgram(program);

// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");

// Create a buffer and put a single clipspace rectangle in
// it (2 triangles)
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1.0, -1.0,
 1.0, -1.0,
-1.0,  1.0,
-1.0,  1.0,
 1.0, -1.0,
 1.0,  1.0]),
gl.STATIC_DRAW);
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);

// draw
gl.drawArrays(gl.TRIANGLES, 0, 6);   
<script id="2d-vertex-shader" type="x-shader/x-vertex">
attribute vec2 a_position;

void main() {
  gl_Position = vec4(a_position, 0, 1);
}
</script>

<script id="2d-fragment-shader" type="x-shader/x-fragment">
void main() {
  gl_FragColor = vec4(0, 1, 0, 1);  // green
}
</script>

Result is draw a green rectangle fo fill the board:

 

7. Performance & Integration

7.1  Web Worker  

  When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. 

  Even there have setInterval and setTimeout which make the multi-threading, but actually its not, javascript only can do one thing at one time.

  A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file. 

  Main Script:

<button onclick="sayHI()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
<output id="result"></output>

<script>
  function sayHI() {
    worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
  }

  function stop() {
    // worker.terminate() from this script would also stop the worker.
    worker.postMessage({'cmd': 'stop', 'msg': 'Bye'});
  }

  function unknownCmd() {
    worker.postMessage({'cmd': 'foobard', 'msg': '???'});
  }

  var worker = new Worker('doWork2.js');

  worker.addEventListener('message', function(e) {
    document.getElementById('result').textContent = e.data;
  }, false);
</script>

DoWorks.js

self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg +
                       '. (buttons will no longer work)');
      self.close(); // Terminates the worker.
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);

 

7.2 XMLHttpRequest2(AJAX2)

  The first version Ajax(XMLHttpRequest1) has the following defects.

  • It only supports the transmission of text data, which can not be used to read and upload binary files.
  • During send and receive data, no progress information and can only be proceed once completed.
  • Same Origin Policy, which can only request data from a server in the same domain, can't cross the domain.

XMLHttpRequest2(new Ajax). Facilitated the old version, have new features below:

  • Can set timeout period of HTTP request.
  • The FormData object can be used to manage the form data.
  • Can upload files.
  • Can request data cross different domain.
  • Can get the binary data of the server side.
  • Can get progress information during transmission.

 

var oReq = new XMLHttpRequest();

oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("load", transferComplete);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);

oReq.open();

// ...

// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
    var percentComplete = oEvent.loaded / oEvent.total;
    // ...
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

function transferComplete(evt) {
  console.log("The transfer is complete.");
}

function transferFailed(evt) {
  console.log("An error occurred while transferring the file.");
}

function transferCanceled(evt) {
  console.log("The transfer has been canceled by the user.");
}

 

 

 

Refers:

http://blog.csdn.net/gane_cheng/article/details/52819118

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5

https://www.w3schools.com/html/html5_intro.asp

https://www.quanzhanketang.com/html/html5_new_elements.html

https://en.wikipedia.org/wiki/Web_storage

https://www.w3.org/TR/IndexedDB-2/

 

posted on 2018-01-31 23:59  两只小蚂蚁  阅读(1320)  评论(0编辑  收藏  举报