HTML5 has a lot of new features. There’s new HTML, CSS and, of course, JavaScript. Officially HTML5 specification and implementation won’t be ready until 2022. Personally I don’t believe in this. Majority of JavaScript features described further are already implemented in modern browsers (e.g. Sarafi, Chrome, Firefox, Opera). Even Internet Explorer gained capability to render canvas and other stuff (supposing we use ExplorerCanvas or Chrome Frame ). Take a closer look at what’s going to make your live better and happier :
New Selectors
How many times have you wondered why there’s getElementById , getElementsByTagName , but there is not getElementByClassName ? New JavaScript API solves this issue:
var elements = document.getElementsByClassName('entry');
Moreover there’s now possibility to fetch elements that match provided CSS syntax!
var elements = document.querySelectorAll("ul li:nth-child(odd)");
var first_td = document.querySelector("table.test > tr > td");
Web Storage
Cookie mechanism has some disadvantages. As W3C said :
- A user could be buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both windows, the ticket currently being purchased would “leak” from one window to the other, potentially causing the user to buy two tickets for the same flight without really noticing.
- Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user’s mailbox, on the client side for performance reasons. Again, cookies do not handle this case well, because they are transmitted with every request.
Well, sessionStorage has been created to let developers cope with first of above troubles. It keeps data in per tab storage. To get along with second one, W3C has introduced localStorage – the persistent storage that never expires.
Look, how simple is saving draft every new character is pressed:
textarea.addEventListener('keyup', function () {
window.localStorage['value'] = area.value;
window.localStorage['timestamp'] = (new Date()).getTime();
}, false);
textarea.value = window.localStorage['value'];
Web SQL Database Storage
What about database accessible directly from JavaScript? Since now we no longer parse, sort, filter data using consuming-lot-of-memory-and-cpu JavaScript loops. We fetch data using well know SQL queries. Look at example:
var db = window.openDatabase("Database Name", "Database Version");
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback);
});
Database is stored on client’s computer so it’s secure.
Offline Application Cache API
Web SQL Storage is available even if client went offline. But if we want create fully-functional offline aplication, we must care about resources like images, CSS, JS and et caetera. It’s high time to familiarize with Application Cache API.
We create cache.manifest file and link to it from html element.
<html
manifest="cache.manifest"
>
File must be served with text/cache-manifest mimetype and contain body like this:
CACHE MANIFEST
CACHE:
index.html
help.html
style
/default.css
images/logo.png
images/backgound.png
NETWORK:
server.cgi
Files listed below CACHE will be cached by browser and available even offline. Files listed after NETWORK are never going to be cached. The application cache automatically updates only if the manifest file changes. It does not automatically update if resources listed in the manifest file change. You may do it manually with JavaScript:
cache = window.applicationCache;
var cacheUpdatereadyListener = function() {
// Swap cache with updated data
cache.swapCache();
}
cache.addEventListener('updateready', cacheUpdatereadyListener, false);
if(cache.status == cache.UPDATEREADY) {
// Update cached data and call updateready listener after
cache.update();
}
You may find full list of Application Cache Event Listeners here .
There is also new window event handler: onOffline. It is fired when internet connection goes down and up . See how we may notice user if there’s change in user’s network connection:
window.addEventListener('offline', function() {
if(navigator.onLine == false) {
alert('We went offline');
} else {
alert('We are online again!');
}
}, true);
Web workers
Workers are API for running scripts in the background independently of any user interface scripts. Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost. Moreover they might be partially replaced by window.setTimeout() function. So have they any advantages? Yes, of course.
- workers are separate JS processes () running in separate threads,
- workers execute concurrently,
- workers don’t block the UI,
- workers allow you to extract up to the last drop of juice from a multicore CPU,
- workers can be dedicated (single tab) or shared among tabs/windows,
- workers can be persistent too (coming soon): they’ll keep running after the browser has quit.
If we call function by setTimeout, the execution of script and UI are suspended. When we call function in worker, it doesn’t affect UI and execution flow in any way. Enough said.
To create Worker, we put JavaScript in separate file and create new Worker instance:
var worker = new Worker(‘extra_work.js');
That’s it. We can communicate with worker using postMessage function and onmessage listener. Messages are sended to all threads in our application:
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.
// some_data could be string, array, object etc.
postMessage(some_data);
There are also so called Shared Workers. Thay use slightly different APIs, since each worker can have multiple connections. An example purpose is logger or application manager. If you are intrested follow fakeworker-js from Google Code.
See demo using workers and similar one without them (will hang your browser).
Web sockets
Let me quote Chromium Blog :
———-
Web Sockets are “TCP for the Web,” a next-generation bidirectional communication technology for web applications. They allow a web server to push data to a browser (COMET). Developers have been using XMLHttpRequest (known as persistent Ajax connection) for such purposes, but XHR makes developing web applications that communicate back and forth to the server unnecessarily complex.
Web Sockets provide a real bidirectional communication channel in your browser. Once you get a Web Socket connection, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. A simple example is included below.
if ("WebSocket" in window) {
var ws = new WebSocket("ws://example.com/service");
ws.onopen = function() {
// Web Socket 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 WebSocket.
}
In addition to the new Web Sockets API, there is also a new protocol (the “web socket protocol “) that the browser uses to communicate with servers. We also developed pywebsocket , which can be used as an Apache extension module, or can even be run as standalone server.
———-
Personally, there’s long way for web sockets to be fully supported by browsers. At this time I would recommend NodeJS or APE Project .
Notifications
Google Chrome has introduced new way to show notifications. They are popping outside browser window and user could see them even if browser is minimalized. Before showing notifications you must ask user for permission to do so. Look at code below and try demo:
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();
}
Show tweets Set notification permissions
Drag and Drop
Everyone knows what is it. Thanks to HTML5 we are able to drag and drop any element into any element, without heavy JavaScript frameworks. There’s also possibility to drag and drop text/images/files from other windows and desktop.
Geolocation
Probably anything special, but since now we may recognize user’s location on frontend as well as backend. Nowadays geolocation is not always accurate and is supported only by Firefox and Safari Mobile.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
map.setCenter(new GLatLng(lat, lng), 13);
map.addOverlay(new GMarker(new GLatLng(lat, lng)));
});
}
Audio and Video manipulation
We can easily embed audio or video on page and super-duper-easily manipulate them with JavaScript.
<audio src="sound.mp3"
controls
>
</audio>
document.getElementById("audio").muted=false;
<video src='movie.mp4'
autoplay
controls
>
</video>
document.getElementById("video").play();
For non-modern browsers you may include html5media . You may also be intrested in HTML5 video player .
Go to audio demo
Go to video demo
Canvas
The best of all! We are able to actually draw in browser. Even second Mac OS if we have patience. Canvas is supported by any browser (even IE thanks to ExplorerCanvas ). There’s huge set of canvas demos at ChromeExperiments.com . There’s CAKE (scenegraph library for the canvas tag). We could write games , physics engines , editors and even whole UI . Flash CS5 will export to HTML5 Canvas and even now we are able to run swf files using pure JavaScript and <canvas> tag (yes, now we can run flash on iPhone).
Useful links
- Check browser support for HTML5 features and view some demos
- Current HTML specification
- HTML5 Presentation
- Detect support for HTML5 features with Modernizr
RT: http://blog.frontendforce.com/2010/04/html5-javascript-api-whats-new/
发表评论
文章已被作者锁定,不允许评论。
-
Chrome、Safari下焦点事件中的select()自动全选
2010-10-23 18:12 1178JS焦点事件自动全选方法: <input ... -
动态添加Javascript链接以增加网页渲染速度
2010-08-28 16:18 823javascript: function addScrip ... -
jQuery & Greasemonkey
2010-08-28 15:01 984How to play nicely with jQuery ... -
关于JavaScript/jQuery事件冒泡
2010-08-25 13:52 909JavaSciprt事件中有两个很重要的特性:事件冒泡以及目标 ... -
Javascript的IE和Firefox兼容性问题集合
2010-08-24 12:29 5741.document.formName.item(&q ... -
jQuery 表格工具集
2010-04-15 21:54 1451新闻来源:noupe.com本文搜集了大量 jQuery 表格 ... -
14条最佳JS代码编写技巧
2010-04-05 02:27 694写任何编程代码,不同的开发 者都会有不同的见解。但参考一 ... -
Javascript 操作select控件大全
2010-04-05 02:18 5781 判断select选项中 是否存在Value=" ... -
Javascript中Element元素定位详解
2010-04-05 01:47 1665scrollHeight: 获取对象的滚动高度。 ...
相关推荐
It’s also great follow-up book for readers of Foundation Game Design with HTML5 and JavaScript (by the same author) who want to add depth and precision to their skills. The game examples in this ...
The HTML5 Programmer’s Reference aims to provide everything a programmer needs for understanding and using the new HTML5 family of standards. Previous HTML standards were focused on defining tags for...
This concise 150 page book will help you create and use practical code analysis tools utilizing the new features of Microsoft’s Roslyn compiler to understand the health of your code and identify ...
New in ECMAScript 5 Part IV: Tips, Tools, and Libraries Chapter 26. A Meta Code Style Guide Chapter 27. Language Mechanisms for Debugging Chapter 28. Subclassing Built-ins Chapter 29. JSDoc: ...
better browsers, performance enhancements, and exciting new facilities. Combined with features such as Canvas, JavaScript offers web developers a truly viable alternative to plug-ins such as Adobe ...
Book Description HTML5 opens up a plethora of new avenues for ... * Those with some experience with HTML, JavaScript, or Flash ActionScript but who are unfamiliar with the new features in HTML5
You’ll get hands-on with all the new features with practical example projects, and find what you need quickly with this book’s modular structure. “Falling Back” sections show you how to create ...
The popular Bootstrap JavaScript library has also now been included natively within MVC 5 providing you, the developer, with a wider range of multi-platform CSS and HTML5 options than ever before ...
Chapter 4: Let’s Get Started With Laravel . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Set Up The Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 ...
The popular Bootstrap JavaScript library has also now been included natively within MVC 5 providing you, the developer, with a wider range of multi-platform CSS and HTML5 options than ever before ...
topics are also discussed such as the Canvas API. XMPP is now more than 10 years old and quite mature. This book covers the 1.0 version of the core protocol. The XMPP protocol parts of this book ...
We’ll start by looking at what a unit test is, what it does, and what it’s good for. Then we’ll build our workflow around them as I introduce the test- driven development process. To round the ...
New features in HTML5 come at a time when web developers are pushing the limits of what is achievable and HTML5, CSS3, and JavaScript have become an important alternative for building rich user ...
WebAssembly is the most promising new technology for the web, allowing browsers, and other JavaScript environments, to run blazing-fast raw binary modules, compiled directly from C, C++ and many other...
WebAssembly is the most promising new technology for the web, allowing browsers, and other JavaScript environments, to run blazing-fast raw binary modules, compiled directly from C, C++ and many other...
The popular Bootstrap JavaScript library has also now been included natively within MVC 5 providing you, the developer, with a wider range of multi-platform CSS and HTML5 options than ever before ...
WebAssembly is the most promising new technology for the web, allowing browsers, and other JavaScript environments, to run blazing-fast raw binary modules, compiled directly from C, C++ and many other...
a new printing API, and support for the Managed Extensibility Framework. What you’ll learn Discover the tools needed for Silverlight 5 development, the roles each plays, and how they interact to ...
And thanks to JavaScript support in AWS Lambda and powerful new serverless API tools like the Claudia.js library, you can build and deploy serverless apps end to end without learning a new language. ...