理解JavaScript中worker事件api,
如果你不是很瞭解Event事件,建議先這篇文章《理解javascript中DOM事件》。
首先,我們需要執行個體一個Worker的對象,瀏覽器會根據新建立的worker對象新開一個介面,此介面會處理用戶端與indexedDB資料庫之間的通訊。這裡的資料庫是指瀏覽器資料庫。如果,你需要判斷瀏覽器是否支援worker對象,詳見如下代碼。或者瀏覽器是否支援indexedDB資料庫,詳見同下,二者判斷最好選擇前者。因為IE不支援indexedDB 。
if(window.Worker){ dosomething }// Workerwindow.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB; if(!window.indexedDB){ dosomething }// indexedDB
之後,worker對象會通過postMessage線程向indexedDB資料庫發送資料,當indexedDB資料庫接收到用戶端發送的資料,首先把資料的索引值儲存並記錄到indexedDB資料庫表裡面,其實相當於把資料儲存在一張結構完整的表內。
於是,indexedDB資料庫會把接收到的資料值扔給新介面處理,當新介面獲得資料並解析之後,會通過postMessage扔回一條資料給資料庫,資料庫接收返回的資料處理的方式和上面一樣,此時indexedDB資料庫會把返回的資料扔給用戶端接受參數的onmessage線程,主線程後面onmessage線程主要是接收傳回的資料。
var txt1 = document.querySelector("#txt1");var txt2 = document.querySelector("#txt2");var result = document.querySelector("#result");window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; if(!window.indexedDB) { console.log("你的瀏覽器不支援IndexedDB"); } if(window.Worker){ var _this = new Worker("../../js/build/scroll_ten1.js"); txt1.onchange = function(){ _this.postMessage([txt1.value,txt2.value]); // e = [txt1.value,txt2.value] console.log("message post to work"); } txt2.onchange = function(){ _this.postMessage([txt1.value,txt2.value]); // e = [txt1.value,txt2.value] console.log("message post to work"); } _this.onmessage = function(s){ //接收到的資料 e result.textContent = s.data; } }
onmessage = function(e){ //e接收Worker.postmessage傳的參數 var s = (e.data[2]*e.data[1]); var workerResult = "result : " + s; postMessage(workerResult); //Worker.onmessage進行回調workerResult參數}
想必大家看了以上的分析之後,肯定在想用Worker能做什嗎?對於這個問題,目前能解決線程的非阻塞問題,如何說起,當使用者改變browser的的尺寸、以及拖動瀏覽器時,主線程訪問後台資料時,並不會中斷資料之間的進程。
支援Worker的browser有哪些?
分享一個連結caniuse,通過這個工具你能更加全面的看到各個瀏覽器的(hack)。
// *注Worker的首字母必須是大寫的
// *注Worker的指令碼目錄必須是HTML能夠訪問到的目錄
以上就是本文的全部內容,希望對大家深入理解JavaScript中worker事件api有所協助。
您可能感興趣的文章:
- 利用google提供的API(JavaScript介面)擷取網站訪問者IP地理位置的代碼詳解
- jQuery validate 中文API 附validate.js中文api手冊
- 百度地圖api應用標註地理位置資訊(js版)
- C# web api傳回型別設定為json的兩種方法
- js 調用百度地圖api並在地圖上進行打點添加標註
- JavaScript中的Web worker多線程API研究