HTML 5 - Web Workers, IndexedDB, Web Messaging (Part-III)
In this article, we will be covering below HTML 5 features:
- Web Worker
- Indexed DB
- Web Messaging
- Web Worker
- JavaScript was designed to run in Single-Threaded environment, that means multiple threads cannot run at the same time.
- Web Workers do these computationally expensive tasks without interrupting UI & typically runs on separate threads.
- Web Workers are background scripts & are relatively heavy-weight. Not to be used in large numbers.
- When Script is executing inside web worker, it cannot access window object.
- Web workers cannot access web page & DOM API.
- Although they cannot block browser UI, they can still consume CPU cycles & to make system less responsive.
var worker = new Worker("scripts/bigLoop.js");
- Above code sets event listeners & communicates with main script which spawned it from main page.
- If application has multiple supporting files, use following way:
importScripts("helper1.js", "helper2.js");
- Once the web worker is spawned, it communicates with the parent page using postMessage().
- It takes single parameter, but based on browser/version, it can be string/JSON object.
- Message passed by worker is accessed using onmessage event in main page.
- Example
- //check browser supportif (Modernizr.webworkers) { //supported var worker = new Worker("test.js");
worker.onmessage = function (event) { console.log(event.data); };
worker.onerror = function (event) { console.log(event.message); };}
- Calling/sending data to parent thread
- //send to parentpostMessage(someObjectWithData);
- Stopping web workers
- Web Workers dont stop by themselves.
- They need to be terminated.
worker.terminate();
- Once terminated, a worker can not be restarted. Instead, need to start a new one.
- IndexedDB
- Alternative for the Web SQL
- Stores key-value pairs
- Non-relational DB
- IndexedDB API is mostly asynchronous
- its not a structured query language
- supports access to same domain
- Example
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTranction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
if (!window.indexedDB) { //handle if browser does not support indexedDB} else { var db, request = window.indexedDB.open("newDatabase", 1);
request.onsuccess = function (event) { db = request.result; };
request.onerror = function (event) {};
request.onupgradeneeded = function (event) { var db = event.target.result; var objectStore = db.objectStore("employee", { keyPath: "id" });
for (var i in testData) { objectStore.add(testData[i]); } };
function add() { var request = db .transaction(["employee"], "readwrite") .objectStore("employee") .add({ id: "1", name: "abc" });
request.onsuccess = function (event) { //record added };
request.onerror = function (event) { //error }; }
function read() { var transaction = db.transaction(["employee"]); var objectStore = transaction.objectStore("employee"); var request = objectStore.get("1"); //pass id
request.onsuccess = function (event) { if (request.result) { //request.result.name } else { //data not found } };
request.onerror = function (event) { //on error }; }
function readall() { var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result;
if (cursor) { //cursor.key, cursor.value.name cursor.continue(); } else { //no record available } }; }}
- Web Messaging
- Allows to share data without DOM.
- Data transfer is possible across domains, protocols n ports.
- Message Event fires cross-document messaging, web sockets, SSE, channel messaging
- Attributes
- data : actual string data
- origin: domain name & ports
- lastEventId: unique id for the current message event
- source: reference to the originating document window
- ports: data sent by message ports
- Before sending the cross document message, we need ton create new browsing context using iframe or new window.
- We can send data using postMessage(), it has two arguments,
- message: message to send
- targetOrigin: origin name
- Send Message
- ...var ifreame = document.querySelector("iframe");var button = document.querySelector("button");
var clickHandler = function () { iframe.contentWindow.postMessage("The Message to send", "originator's url");};
button.addEventListner("click", clickHandler, false);...
- Receiving Message
...var messageEventHandler = function (event) { if (event.origin == "my origin") { //consume event.data }};
window.addEventListner("message", messageEventHandler, false);...
- Channel Messaging
- It's a Two-Way communication between browsing context. Communication across multiple origins.
- While creating messageChannel, it internally creates two ports to sending the data & forwarded to another browsing context.
- We are sending data from one iframe to another.
Happy Learning :)
- JavaScript was designed to run in Single-Threaded environment, that means multiple threads cannot run at the same time.
- Web Workers do these computationally expensive tasks without interrupting UI & typically runs on separate threads.
- Web Workers are background scripts & are relatively heavy-weight. Not to be used in large numbers.
- When Script is executing inside web worker, it cannot access window object.
- Web workers cannot access web page & DOM API.
- Although they cannot block browser UI, they can still consume CPU cycles & to make system less responsive.
- var worker = new Worker("scripts/bigLoop.js");
- Above code sets event listeners & communicates with main script which spawned it from main page.
- If application has multiple supporting files, use following way:
- importScripts("helper1.js", "helper2.js");
- Once the web worker is spawned, it communicates with the parent page using postMessage().
- It takes single parameter, but based on browser/version, it can be string/JSON object.
- Message passed by worker is accessed using onmessage event in main page.
- Example
- //check browser supportif (Modernizr.webworkers) {//supportedvar worker = new Worker("test.js");worker.onmessage = function (event) {console.log(event.data);};worker.onerror = function (event) {console.log(event.message);};}
- Calling/sending data to parent thread
- //send to parentpostMessage(someObjectWithData);
- Stopping web workers
- Web Workers dont stop by themselves.
- They need to be terminated.
- worker.terminate();
- Once terminated, a worker can not be restarted. Instead, need to start a new one.
- Alternative for the Web SQL
- Stores key-value pairs
- Non-relational DB
- IndexedDB API is mostly asynchronous
- its not a structured query language
- supports access to same domain
- Example
- window.indexedDB =window.indexedDB ||window.mozIndexedDB ||window.webkitIndexedDB ||window.msIndexedDB;window.IDBTransaction =window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTranction;window.IDBKeyRange =window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;if (!window.indexedDB) {//handle if browser does not support indexedDB} else {var db,request = window.indexedDB.open("newDatabase", 1);request.onsuccess = function (event) {db = request.result;};request.onerror = function (event) {};request.onupgradeneeded = function (event) {var db = event.target.result;var objectStore = db.objectStore("employee", { keyPath: "id" });for (var i in testData) {objectStore.add(testData[i]);}};function add() {var request = db.transaction(["employee"], "readwrite").objectStore("employee").add({ id: "1", name: "abc" });request.onsuccess = function (event) {//record added};request.onerror = function (event) {//error};}function read() {var transaction = db.transaction(["employee"]);var objectStore = transaction.objectStore("employee");var request = objectStore.get("1"); //pass idrequest.onsuccess = function (event) {if (request.result) {//request.result.name} else {//data not found}};request.onerror = function (event) {//on error};}function readall() {var objectStore = db.transaction("employee").objectStore("employee");objectStore.openCursor().onsuccess = function (event) {var cursor = event.target.result;if (cursor) {//cursor.key, cursor.value.namecursor.continue();} else {//no record available}};}}
- Allows to share data without DOM.
- Data transfer is possible across domains, protocols n ports.
- Message Event fires cross-document messaging, web sockets, SSE, channel messaging
- Attributes
- data : actual string data
- origin: domain name & ports
- lastEventId: unique id for the current message event
- source: reference to the originating document window
- ports: data sent by message ports
- Before sending the cross document message, we need ton create new browsing context using iframe or new window.
- We can send data using postMessage(), it has two arguments,
- message: message to send
- targetOrigin: origin name
- Send Message
- ...var ifreame = document.querySelector("iframe");var button = document.querySelector("button");var clickHandler = function () {iframe.contentWindow.postMessage("The Message to send", "originator's url");};button.addEventListner("click", clickHandler, false);...
- Receiving Message
- ...var messageEventHandler = function (event) {if (event.origin == "my origin") {//consume event.data}};window.addEventListner("message", messageEventHandler, false);...
- Channel Messaging
- It's a Two-Way communication between browsing context. Communication across multiple origins.
- While creating messageChannel, it internally creates two ports to sending the data & forwarded to another browsing context.
- We are sending data from one iframe to another.
Comments
Post a Comment