WebWorker,EventSource,Ajax,WebSocket,WebRTC共同構成網絡生態中主要的部分,WebWoker多線程的出現,使得Javascript更容易實現異步編程,特別是在耗時任務使得Javascript更加健壯。javascript
支持LocalStorage數據存儲html
webview.getSettings().setDomStorageEnabled(true); webview.getSettings().setAppCacheMaxSize(1024*1024*25); String appCachePath = ctx.getApplicationContext().getCacheDir().getAbsolutePath(); webview.getSettings().setAppCachePath(appCachePath); webview.getSettings().setAllowFileAccess(true); webview.getSettings().setAppCacheEnabled(true);
2.支持多線程(Wokers與ShareWorker API)
html5
settings.setAllowFileAccess(true); settings.setAppCacheEnabled(true); settings.setAllowContentAccess(true); settings.setAllowFileAccessFromFileURLs(true);
1.實現workers.js子線程java
var i=0; function timedCount() { i=i+1; self.postMessage(i); setTimeout("timedCount()",500); } self.onmessage = function(event) { var method = event.data.method; var args = event.data.args; self.postMessage({method: method, reply: args }); }; timedCount();
在html5中實現WebWorker的調用該android
<script type="text/javascript" > if(!!window.Worker&& typeof(Worker)!=="undefined") { window.worker = new Worker("./workers.js"); window.worker.onmessage = function (event) { console.dir(event.data); document.querySelector('#span_title').innerHtml = event; }; worker.onerror(function(event) { console.log(event); }); }else{ alert('不支持 Web Worker'); } window.onbeforeunload = function() { window.worker.terminate(); } </script>
2.固然,同一個頁面也能實現主線程與子線程通訊web
重點:<script id="worker" type="app/worker"></script>編程
<!DOCTYPE html> <body> <script id="worker" type="app/worker"> addEventListener('message', function() { postMessage('Work done!'); }, false); </script> <script type="text/javascript"> (function() { var blob = new Blob([document.querySelector('#worker').textContent]); var url = window.URL.createObjectURL(blob); var worker = new Worker(url); worker.addEventListener('message', function(e) { console.log(e.data); }, false); worker.postMessage(''); })(); </script> </body> </html>
3.再來看看ShareWorkerapi
ShareWorker表示建立一個線程,能被其餘同源同域的窗口,iframe都能訪問,這也就是相似Java中的多線程中的資源共享,固然這裏應該不會出現同步問題。網絡
<!DOCTYPE HTML> <title>Shared workers: demo 1</title> <pre id="log">Log:</pre> <script> var worker = new SharedWorker('workers.js',"com.my.share.webwoker"); //提供第二個參數,參數一致才能被共享 var log = document.getElementById('log'); worker.port.onmessage = function(e) { // note: not worker.onmessage! log.textContent += '\n' + e.data; } </script>
固然,還有ServiceWorker,這裏就不介紹了多線程
http://javascript.ruanyifeng.com/htmlapi/webworker.html#toc7
----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------