html5 api

目录:

  1. WebWorker
  2. ServiceWorker
  3. fetch api
  4. cache api
  5. webSocket

1. WebWorker

  1. https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
  2. http://www.html5rocks.com/zh/tutorials/workers/basics/
  3. Web Workers are a mechanism by which a script operation can be made to run in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

    Web Workers是一个可以独立于一个webapp主进程的后台线程。Web Workers独立线程允许ui主线程不卡顿。

  4. Web Worker分为专用worker(DedicatedWorker)、共享worker(SharedWorker)、ServiceWorker、AudioWorkers、ChromeWorkers。DedicatedWorker和页面相关,每个页面启动自己的worker;SharedWorker和domain相关联;ServiceWorker和domain+path相关;ChromeWorkers是用来开发浏览器扩展的。
  5. Web Worker的全局作用域是self,不同于window,操作不了dom操作,访问不了window上的属性和方法;但可以通过self访问一些cache、indexDB、*Storage、webSockets等。
  6. Web Worker与ui主进程通过postmessage进行通信。

    DedicatedWorkers Demo:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>webworker</title>
    </head>
    <body>
        <script type="text/javascript">
            if(window.Worker) {
                var worker = new Worker("worker.js");
                worker.addEventListener("message", function(e) {
    
                });
    
                worker.postMessage({type: "url", url: location.href});
            }
        </script>
    </body>
    </html>
    

    //worker.js

    var timestamp = new Date().getTime();
    self.addEventListener('message', function(e) {
        console.log(timestamp);
          self.postMessage(e.data);
    }, false);
    

2. ServiceWorkers

  1. https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
  2. http://www.html5rocks.com/en/tutorials/service-worker/introduction/
  3. ServiceWorkers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server.

    ServiceWorkers作用相当于在多个webApps与浏览器、服务器之间做一层代理;它允许离线应用的实现、拦截请求并基于是否有网络做一些操作(从缓存里读取数据或者从服务端重新拉去)。

  4. ServiceWorker作为一个worker是不能直接操作dom的,但是可以通过message api与主ui进程交互。
  5. ServiceWorker是为了解决AppCache的一些局限,比如多页应用等。(目前在使用AppCache的地方,会提示建议使用ServiceWorker)
  6. A service worker has a lifecycle which is completely separate from your web page.

    一个Service Worker的生命周期是完全独立于页面的。只和origin+path相关,可以服务于多个页面。

    demo-html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>service worker</title>
    </head>
    <body>
        <div class="test">serviceworker</div>
        <script>
            if(navigator.serviceWorker) {
                var a = navigator.serviceWorker.register("service.js").then(function(registration) {
                    console.log("register success");
                }).catch(function(err) {
                    console.log(err);
                });
    
                setTimeout(function() {
                    fetch("data.json").then(function(data) {
                        console.log(data);
                    });
                }, 2000);
            }
        </script>
    </body>
    </html>
    

    demo-js:

    var cache,
        cacheList = [
            "data.json"
        ];
    self.addEventListener("install", function(evt) {
        caches.open("service").then(function(cache) {
            cache.addAll(cacheList);
        });
    });
    self.addEventListener("fetch", function(evt) {
        var res = caches.match(evt.request).then(function(response) {
            if (response) {
                console.log("cached hitted;");
                return response;
            }
    
            return fetch(evt.request);
        });
        evt.respondWith(res);
    });
    

3. fetch api

  1. http://www.w3ctech.com/topic/854?&from=androidqq
  2. XMLHttpRequest对象把所有的操作、状态融合到一个对象里,不符合职责分离的原则;并且基于事件的操作与目前的Promise模式不太搭;
  3. fetch api正式基于这样的优化设计出来的。fetch api完美的支持Promise;并且fetch api可以与ServiceWorker结合改善离线体验、保持可扩展性。
  4. fetch api定了3个对象类Headers、Request、Response对应请求头、请求、请求结果三个对象;以及一个方法接口fetch来调用执行fetch请求。
  5. fetch api的使用只能是https或者localhost

    demo,XMLHttpRequest和fetch对于网络资源请求可以实现同样的效果,只是形式不一样,并且fetch可以与ServiceWorkers结合:

    var xhr = new XMLHttpRequest();
    xhr.open("get", "data.json", true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4) {
            console.log("xhr:");
            console.log(xhr.responseText);
        }
    }
    xhr.send(null);
    
    fetch("data.json").then(function(res) {
        console.log("fetch:");
        console.log(res);
    });
    
    //复杂的fetch
    var headers = new Headers({
        method: "get"
    });
    var request = new Request("data.json", headers);
    fetch(request).then(function(res) {
        console.log("fetch2:");
        console.log(res);
    });
    

4. cache api

  1. https://developer.mozilla.org/en-US/docs/Web/API/Cache
  2. cache api的使用只能是https或者localhost
  3. cache api是和origin相关的。
  4. The Cache interface provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle.

    Cache Api是Request/Response直接映射关系的缓存的机制;可以作为ServiceWorker生存周期的一部分。

  5. Cache Api的接口:add、addAll、put、match、keys.

    demo:

    caches.open("demo").then(function(cache) {
        console.log(cache);
        cache.add("data.json").then(function() {
            cache.match("data.json").then(function(response) {
                console.log(response);
            });
        });
    });
    

5. WebSocket

  1. https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
  2. https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers
  3. https://tools.ietf.org/html/rfc6455
  4. The protocol consists of an opening handshake
    followed by basic message framing, layered over TCP. The goal of
    this technology is to provide a mechanism for browser-based
    applications that need two-way communication with servers that does
    not rely on opening multiple HTTP connections (e.g., using
    XMLHttpRequest or <iframe>s and long polling).

    >这个协议基于TCP组成,先是通过一个开放的handshake,随后才是基本的数据序列。这个技术的目标是提供一个基于浏览器的应用与服务端的双向通信,这项技术并不依赖于多个HTTP连接,使用其他技术如XMLHttpRequest或者iframes或者长轮询;
    
  5. The WebSocket Protocol is an independent TCP-based protocol. Its
    only relationship to HTTP is that its handshake is interpreted by
    HTTP servers as an Upgrade request.

    >WebSocket协议是一个完全独立的基于TCP的协议,它与Http的关系仅仅是它的handshake是通过Http来发送协议升级请求的。
    
  6. 目前WebSocket协议handshake实现利用现有的Http基础来实现的,但并不表示未来WebSocket将局限于Http。
  7. 创建WebSocket连接,将分为2步:第一步,基于Http的handshake,handshake即是处理WebSocket基于http的连接的建立(通过http头信息,升级http协议到websocket,并建立连接);第二个,基于tcp正常的数据传输。
  8. WebSocket和Http协议一样都是应用层协议,而socket只是操作tcp、udp的接口协议。

    demo-server:

    var WebSocketServer = require('ws').Server,
        server = new WebSocketServer({port: 8126});
    
    server.on('connection', function connection(ws) {
        console.log("connected");
        ws.on('message', function incoming(message) {
            console.log('received: %s;', message);
            ws.send("something");
        });
    });
    

    demo-browser:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>web socket
        </title>
    </head>
    <body>
        <script>
            var connection = new WebSocket("ws://127.0.0.1:8126");
            connection.onopen = function(evt) {
                console.log("open");
                connection.send("test");
            }
            connection.onmessage = function(evt) {
                console.log("message");
            }
            connection.onclose = function(evt) {
                console.log("close");
            }
        </script>
    </body>
    </html>