HTML5 技術體系中的 JavaScript

簡介

在 HTML 5 的技術體系當中,JavaScript 的語法並沒有甚麼的變動,但是 JavaScript 所支援的函式庫則有相當大的進步,像是 Web Storage、Web SQL Database、XDomain Communication、Notification、Geolocation API 等,都是原先 JavaScript 函式庫所不曾提供的。

這些新增的 API 大致可以分為下列數類,Client Side Storage (Web SQL Database, App Cache, Web Storage)
Communication (Web Sockets, Worker Workers)、Desktop experience (Notifications, Drag and Drop API)、
與 Geolocation 等。

選擇器

在 DHTML 物件模型 DOM 的選擇器上,JavaScript 增加了 getElementsByClassName()、querySelectorAll() 等函數,

Finding elements by class (DOM API)
var el = document.getElementById('section1');
el.focus();

var els = document.getElementsByTagName('div');
els[0].focus();

var els = document.getElementsByClassName('section');
els[0].focus();
Finding elements by CSS syntax (Selectors API)
var els = document.querySelectorAll("ul li:nth-child(odd)");
var els = document.querySelectorAll("table.test > tr > td");

WebStorage

// use localStorage for persistent storage
// use sessionStorage for per tab storage
textarea.addEventListener('keyup', function () {
  window.localStorage['value'] = area.value;
  window.localStorage['timestamp'] = (new Date()).getTime();
}, false);
textarea.value = window.localStorage['value'];

Save text value on the client side (crash-safe)

Web SQL Database

var db = window.openDatabase("Database Name", "Database Version");
db.transaction(function(tx) {
  tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback);
});

See the generated database: Developer > Developer Tools > Storage

Application Cache API

<html manifest="cache-manifest">
window.applicationCache.addEventListener('checking', updateCacheStatus, false);
CACHE MANIFEST

# version 1

CACHE:
/html5/src/refresh.png
/html5/src/logic.js
/html5/src/style.css
/html5/src/background.png

Turn off your internet connection and refresh!

Web Workers

main.js:
  var worker = new Worker(‘extra_work.js');
  worker.onmessage = function(event) { alert(event.data); };

extra_work.js:
  // do some work; when done post message.
  postMessage(some_data);

Web Socket

var socket = new WebSocket(location);
socket.onopen = function(event) {
  socket.postMessage(“Hello, WebSocket”);
}
socket.onmessage = function(event) { alert(event.data); }
socket.onclose = function(event) { alert(“closed”); }

Notification

if (window.webkitNotifications.checkPermission() == 0) {
  // you can pass any url as a parameter
  window.webkitNotifications.createNotification(tweet.picture, tweet.title, 
      tweet.text).show();
} else {
  window.webkitNotifications.requestPermission();
}

Drag and Drop

document.addEventListener('dragstart', function(event) {
   event.dataTransfer.setData('text', 'Customized text');
   event.dataTransfer.effectAllowed = 'copy';
}, false);

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);
  });
}

檢測流覽器是否支持某屬性

alert( 'pattern' in document.createElement('input') ) // boolean;
<script> 
if (!'pattern' in document.createElement('input') ) { 
// do client/server side validation 
} 
</script>