1. Offline buffering of H5

HTML5’s offline storage is based on a newly created.appCache file, where parsed lists of offline storage resources are stored like cookies. Later, when the network is offline, the browser displays the data stored offline. HTML5 offline Cache, also known as Application Cache, is a block of the browser’s Cache. To store data in this Cache, you can use a manifest file that lists the resources to download and Cache.

<html manifest="haorooms.appcache">
Copy the code

Parsing the listing

Before you start, take a look at the manifest (a.appcache file), which looks something like this.

CACHE MANIFEST #version 1.2.2 CACHE #css http://www.haorooms.com/theme/assets/style.css #js http://www.haorooms.com/theme/assets/js/main.js #img http://static.hyb.dev.ipo.com/css/wifi/pc/images/logo-fk1.png http://static.hyb.dev.ipo.com/css/wifi/images/favicon.ico NETWORK: # all resources written here will never be buffered # Asterisks can be used to indicate that all other resources/files require an Internet connection (except those listed below in CACHE) * FALLBACK: /html5/ /404.html # The FALLBACK section below specifies that if an Internet connection cannot be established, all files in the /html5/ directory should be replaced with "404.html" :Copy the code

The manifest file can be divided into three parts:

CACHE MANIFEST - Files listed under this heading will be cached after the first download NETWORK - files listed under this heading require a connection to the server, And not cached FALLBACK - Files listed under this heading specify a FALLBACK page when the page is not accessible (such as a 404 page)Copy the code

When online, the user agent reads the manifest every time it visits a page. If it changes, reload the resources in the entire list

Update the buffer

Update the manifest file: If you add or delete files to the manifest file, you can update the cache. If you change js and do not add or delete files, the version number, timestamp, or MD5 code in the preceding example can be used to update the manifest file

Second, through javascript operation: HTML5 introduced js operation offline cache method, the following JS can manually update the local cache. window.applicationCache.update();

Clear the browser cache: if the user clears the browser cache (manually or with some other tool), the file will be redownloaded.

Second, the Web Worker

Js is single thread, that is to say, only one thing can be done at present, and other tasks need to wait for execution. With the continuous development of the computer field, especially the emergence of multi-core CPU, single thread brings a lot of inconvenience and can not give full play to the computing power of the computer.

The function of Web worker is to allow us to create multiple processes, and the created sub-threads receive the control of the main thread. The main thread can appropriately allocate some tasks to the sub-threads, so that the sub-threads can run in the background without interference, and then return to the main thread after the execution of the sub-threads is completed. The advantage of this is that when computationally intensive or high-latency tasks are taken on by Worker threads, the main thread (usually responsible for UI interactions) will flow smoothly and will not be blocked or slowed down.

Some points to be aware of when using Web Workers

1. DOM restriction: Worker child threads cannot call our Document, window and parent objects, but can use navigator and location objects. 2. The Worker thread and the main thread are not in the same context. They cannot communicate directly and must be completed through messages. 3. You cannot use alert and confirm, but you can use XMLHttpRequest to send Ajax requests. 4. The Worker thread cannot read local files, that is, cannot open the local file system (file://), and the scripts it loads must come from the network.Copy the code

Basic usage

/ / main thread
var worker = new Worker('work.js'); // Create a web worker
// The argument to the Worker() constructor is a script file that is the task to be performed by the Worker thread. Since the Worker cannot read local files, the script must come from the network. If the download does not succeed (such as a 404 error), the Worker silently fails.

// Send a message to the child thread
worker.postMessage('Hello World');
worker.postMessage({method: 'echo'.args: ['Work']});

// Listen for messages returned by child threads
worker.onmessage = function (event) {
  console.log('Received message ' + event.data);
  // event.data can get data
  doSomething();
}

function doSomething() {
  // Execute the task
  worker.postMessage('Work done! ');
  
  worker.terminate(); // Close the child thread
}

// Main thread listening error
worker.onerror(function (event) {
  console.log([
    'ERROR: Line ', e.lineno, ' in ', e.filename, ':', e.message
  ].join(' '));
});
Copy the code
// Receive the message
self.addEventListener('message'.function (e) {
  self.postMessage('You said: ' + e.data);
}, false);
// self represents the child thread itself, the global object of the child thread.

// Or you could write it this way
self.addEventListener('message'.function (e) {
  var data = e.data; // Receives the incoming message content
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg);
      self.close(); // Close itself
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);
Copy the code

Third, the WebSocket

WebSocket is a network communication protocol, which is needed for many advanced functions. We might wonder, why do we need this protocol when we already have HTTP for web communications? Very simple, we all know that HTTP protocol can only be initiated by the client, the server can not actively push content. Our previous solution was polling on the client side, but this was very resource-intensive. WebSocket provides a solution.

The protocol identifier is WS (or WSS if encrypted), and the server URL is the URL.

Example client script

var ws = new WebSocket("wss://echo.websocket.org"); / / create a socket

// Callback after successful connection
ws.onopen = function(evt) { 
  console.log("Connection open ..."); 
  // Send the message
  ws.send("Hello WebSockets!");
};

// Listen for messages to return
ws.onmessage = function(event) {
  console.log( "Received Message: " + event.data);
  // The server data can be either text or binary (bloB objects or Arraybuffer objects).
  if(typeof event.data === String) {
    console.log("Received data string");
  }

  if(event.data instanceof ArrayBuffer) {var buffer = event.data;
    console.log("Received arraybuffer");
  }
  // Close the connection
  ws.close();
};

// Close the callback function
ws.onclose = function(evt) {
  console.log("Connection closed.");
};      

// An error callback occurred
socket.onerror = function(event) {
  // handle error event
};

Copy the code