SlideShare a Scribd company logo
Web Workers
JavaScript was designed to run in a single-threaded environment, meaning multiple
scripts cannot run at the same time. Consider a situation where you need to handle
UI events, query and process large amounts of API data, and manipulate the DOM.
JavaScript will hang your browser in situation where CPU utilization is high. Let us
take a simple example where JavaScript goes through a big loop -
What is Web Workers?
The situation explained above can be handled using Web Workers who will do all
the computationally expensive tasks without interrupting the user interface and
typically run on separate threads.
Web Workers allow for long-running scripts that are not interrupted by scripts that
respond to clicks or other user interactions, and allows long tasks to be executed
without yielding to keep the page responsive.
Web Workers are background scripts and they are relatively heavy-weight, and are not
intended to be used in large numbers. For example, it would be inappropriate to launch one
worker for each pixel of a four megapixel image.
When a script is executing inside a Web Worker it cannot access the web page's window object
(window.document), which means that Web Workers don't have direct access to the web page
and the DOM API. Although Web Workers cannot block the browser UI, they can still consume
CPU cycles and make the system less responsive.
How Web Workers Work?
Web Workers are initialized with the URL of a JavaScript file, which contains the code the
worker will execute. This code sets event listeners and communicates with the script that
spawned it from the main page. Following is the simple syntax -
var worker = new Worker( 'bigLoop.js' );
If the specified javascript file exists, the browser will spawn a new worker thread, which is
downloaded asynchronously. If the path to your worker returns an 404 error, the worker will
fail silently.
If your application has multiple supporting JavaScript files, you can import them
importScripts() method which takes file name(s) as argument separated by comma as follows -
importScripts("he1per.js", "anotherHe1per.js");
Once the Web Worker is spawned, communication between web worker and its parent page is
done using the postMessage() method. Depending on your browser/version, postMessage()
can accept either a string or JSON object as its single argument.
Message passed by Web Worker is accessed using onmessage event in the main page. Now let
us write our bigLoop example using Web Worker. Below is the main page (hello.htm) which
will spawn a web worker to execute the loop and to return the final value of variablej -
< ! DOCTYPE HTML >
<html>
<head>
< title>Big for loop</title>
<script> var worker new Worker( 'bigLoop.js ' ) ;
worker.onmessage = function (event alert ( "Completed event .
data + "iterations"
function sayHe110 alert ("Hello sir. . ");
< / script >
</head>
<body>
<input type ="button" onclick="sayHe110()" value="">
</body>
</html>
Stopping Web Workers
Web Workers don't stop by themselves but the page that started them can stop them by
calling terminate() method.
worker . terminate();
A terminated Web Worker will no longer respond to messages or perform any additional
computations. You cannot restart a worker; instead, you can create a new worker using the
same URL.
Handling Errors
The following shows an example of an error handling function in a Web Worker JavaScript file
that logs errors to the console. With error handling code, above example would become as
following -
A terminated Web Worker will no longer respond to messages or perform any
additional computations. You cannot restart a worker; instead, you can create a new
worker using the same URL.
Handling Errors
The following shows an example of an error handling function in a Web Worker
JavaScript file that logs errors to the console. With error handling code, above
example would become as following -
< ! DOCTYPE HTML >
<html>
<head>
<tit1e>Big for loop</title>
<script> var worker new Worker( 'bigLoop.js ' ) ;
worker . onmessage function (event alert ( " Completed event . data +
"iterations")
worker . onerror function (event) { console. log(event.message, event);
function sayHe110 alert("He110 sir")
< / script >
</head>
<body>
<input type =" button " onclick="sayHe110()" value="Say Hello"/ >
</body>
</html>
Checking for Browser Support
Following is the syntax to detect a Web Worker feature support available in a browser -
< ! DOCTYPE HTML >
<html>
<head>
<tit1e>Big for loop</title>
<script src=" /js/modernizr-l. 5 . min . js " ></script>
<script> function myFunction() {
if (modernizr.webworkers) { alert("Congratu1ation! ! you have web workers
support. " else alert ("Sorry! ! you do not have web workers support. "
</script>
</head>
<button onclick myFunction()">C1ick me</button>
</html>
This will produce the following result -
CLICK ME

More Related Content

What's hot (20)

Groovy with Mule
Groovy with MuleGroovy with Mule
Groovy with Mule
irfan1008
 
2310 b 06
2310 b 062310 b 06
2310 b 06
Krazy Koder
 
Groovy in Mule
Groovy in MuleGroovy in Mule
Groovy in Mule
Praneethchampion
 
Java Servlets Part 2
Java Servlets Part 2Java Servlets Part 2
Java Servlets Part 2
Gurpreet singh
 
Simple Java component in Mule
Simple Java component in MuleSimple Java component in Mule
Simple Java component in Mule
Christian Hipolito
 
Amitesh Madhur - Web workers, HTML 5
Amitesh Madhur - Web workers, HTML 5Amitesh Madhur - Web workers, HTML 5
Amitesh Madhur - Web workers, HTML 5
Amitesh Madhur
 
AJAX
AJAXAJAX
AJAX
Akhil Kumar
 
Java Servlet part 3
Java Servlet part 3Java Servlet part 3
Java Servlet part 3
Gurpreet singh
 
Js unit testing
Js unit testingJs unit testing
Js unit testing
Mihail Irintchev
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
RubyOnRails_dude
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.net
Sireesh K
 
Magnolia CMS Tasks & Workflows
Magnolia CMS Tasks & WorkflowsMagnolia CMS Tasks & Workflows
Magnolia CMS Tasks & Workflows
Magnolia
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
Sergey Romaneko
 
Ajax control tool kit
Ajax control tool kitAjax control tool kit
Ajax control tool kit
Vidhi Patel
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
Milan Korsos
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Omnia Helmi
 
Web Os Hands On
Web Os Hands OnWeb Os Hands On
Web Os Hands On
360|Conferences
 
Anypoint lessons
Anypoint lessonsAnypoint lessons
Anypoint lessons
Dwight Cavalcanti
 
Cache for community edition
Cache for community editionCache for community edition
Cache for community edition
irfan1008
 
2310 b 03
2310 b 032310 b 03
2310 b 03
Krazy Koder
 
Groovy with Mule
Groovy with MuleGroovy with Mule
Groovy with Mule
irfan1008
 
Amitesh Madhur - Web workers, HTML 5
Amitesh Madhur - Web workers, HTML 5Amitesh Madhur - Web workers, HTML 5
Amitesh Madhur - Web workers, HTML 5
Amitesh Madhur
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.net
Sireesh K
 
Magnolia CMS Tasks & Workflows
Magnolia CMS Tasks & WorkflowsMagnolia CMS Tasks & Workflows
Magnolia CMS Tasks & Workflows
Magnolia
 
Ajax control tool kit
Ajax control tool kitAjax control tool kit
Ajax control tool kit
Vidhi Patel
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
Milan Korsos
 
Cache for community edition
Cache for community editionCache for community edition
Cache for community edition
irfan1008
 

Similar to Html web workers (20)

Web workers
Web workersWeb workers
Web workers
Surbhi Mathur
 
Web workers
Web workersWeb workers
Web workers
Surbhi Mathur
 
25250716 seminar-on-ajax text
25250716 seminar-on-ajax text25250716 seminar-on-ajax text
25250716 seminar-on-ajax text
Kamleshh Chandnani
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
rumsan
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
Rob Davarnia
 
Beyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsBeyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 Apps
Marcos Caceres
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
Sakthi Bro
 
Ajax
AjaxAjax
Ajax
husnara mohammad
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
ch samaram
 
4007655 introduction-to-javascript
4007655 introduction-to-javascript4007655 introduction-to-javascript
4007655 introduction-to-javascript
Vikash Chandra
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
Jaya Kumari
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
Mohammed Hussein
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
M Ramya
M RamyaM Ramya
M Ramya
st anns PG College,Mallapur,Hyderabad, India
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
MAGNA COLLEGE OF ENGINEERING
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)
Shrijan Tiwari
 
How to Use AJAX in PHP and jQuery.pdf
How to Use AJAX in PHP and jQuery.pdfHow to Use AJAX in PHP and jQuery.pdf
How to Use AJAX in PHP and jQuery.pdf
semsem20021
 
Ajax
AjaxAjax
Ajax
anandha ganesh
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnitWriting and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Lecture-15.pptx
Lecture-15.pptxLecture-15.pptx
Lecture-15.pptx
vishal choudhary
 

More from AbhishekMondal42 (20)

Oss evaluation-certification-oss-financial-advantages
Oss evaluation-certification-oss-financial-advantagesOss evaluation-certification-oss-financial-advantages
Oss evaluation-certification-oss-financial-advantages
AbhishekMondal42
 
Word press 01
Word press 01Word press 01
Word press 01
AbhishekMondal42
 
Word press posts(preview &amp; publish)
Word press posts(preview &amp; publish)Word press posts(preview &amp; publish)
Word press posts(preview &amp; publish)
AbhishekMondal42
 
Word press posts(add , edit , delete post)
Word press posts(add , edit , delete post)Word press posts(add , edit , delete post)
Word press posts(add , edit , delete post)
AbhishekMondal42
 
Word press pages(edit and delete)
Word press pages(edit and delete)Word press pages(edit and delete)
Word press pages(edit and delete)
AbhishekMondal42
 
Word press pages(add)
Word press pages(add)Word press pages(add)
Word press pages(add)
AbhishekMondal42
 
Word press media(add,insert,delete)
Word press media(add,insert,delete)Word press media(add,insert,delete)
Word press media(add,insert,delete)
AbhishekMondal42
 
Word press media library
Word press media libraryWord press media library
Word press media library
AbhishekMondal42
 
Word press widget management
Word press  widget managementWord press  widget management
Word press widget management
AbhishekMondal42
 
Word press view plugins
Word press  view pluginsWord press  view plugins
Word press view plugins
AbhishekMondal42
 
Word press user roles
Word press  user rolesWord press  user roles
Word press user roles
AbhishekMondal42
 
Word press theme management
Word press  theme managementWord press  theme management
Word press theme management
AbhishekMondal42
 
Word press personal profile
Word press  personal profileWord press  personal profile
Word press personal profile
AbhishekMondal42
 
Word press moderate comments
Word press  moderate commentsWord press  moderate comments
Word press moderate comments
AbhishekMondal42
 
Word press install plugins
Word press  install pluginsWord press  install plugins
Word press install plugins
AbhishekMondal42
 
Word press edit users
Word press  edit usersWord press  edit users
Word press edit users
AbhishekMondal42
 
Word press edit tags
Word press  edit tagsWord press  edit tags
Word press edit tags
AbhishekMondal42
 
Word press edit links
Word press  edit linksWord press  edit links
Word press edit links
AbhishekMondal42
 
Word press edit comments
Word press  edit commentsWord press  edit comments
Word press edit comments
AbhishekMondal42
 
Word press delete users
Word press  delete usersWord press  delete users
Word press delete users
AbhishekMondal42
 
Oss evaluation-certification-oss-financial-advantages
Oss evaluation-certification-oss-financial-advantagesOss evaluation-certification-oss-financial-advantages
Oss evaluation-certification-oss-financial-advantages
AbhishekMondal42
 
Word press posts(preview &amp; publish)
Word press posts(preview &amp; publish)Word press posts(preview &amp; publish)
Word press posts(preview &amp; publish)
AbhishekMondal42
 
Word press posts(add , edit , delete post)
Word press posts(add , edit , delete post)Word press posts(add , edit , delete post)
Word press posts(add , edit , delete post)
AbhishekMondal42
 
Word press pages(edit and delete)
Word press pages(edit and delete)Word press pages(edit and delete)
Word press pages(edit and delete)
AbhishekMondal42
 
Word press media(add,insert,delete)
Word press media(add,insert,delete)Word press media(add,insert,delete)
Word press media(add,insert,delete)
AbhishekMondal42
 
Word press widget management
Word press  widget managementWord press  widget management
Word press widget management
AbhishekMondal42
 
Word press theme management
Word press  theme managementWord press  theme management
Word press theme management
AbhishekMondal42
 
Word press personal profile
Word press  personal profileWord press  personal profile
Word press personal profile
AbhishekMondal42
 
Word press moderate comments
Word press  moderate commentsWord press  moderate comments
Word press moderate comments
AbhishekMondal42
 
Word press install plugins
Word press  install pluginsWord press  install plugins
Word press install plugins
AbhishekMondal42
 

Recently uploaded (20)

Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 

Html web workers

  • 2. JavaScript was designed to run in a single-threaded environment, meaning multiple scripts cannot run at the same time. Consider a situation where you need to handle UI events, query and process large amounts of API data, and manipulate the DOM. JavaScript will hang your browser in situation where CPU utilization is high. Let us take a simple example where JavaScript goes through a big loop - What is Web Workers? The situation explained above can be handled using Web Workers who will do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads. Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
  • 3. Web Workers are background scripts and they are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image. When a script is executing inside a Web Worker it cannot access the web page's window object (window.document), which means that Web Workers don't have direct access to the web page and the DOM API. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive. How Web Workers Work? Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will execute. This code sets event listeners and communicates with the script that spawned it from the main page. Following is the simple syntax - var worker = new Worker( 'bigLoop.js' );
  • 4. If the specified javascript file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. If the path to your worker returns an 404 error, the worker will fail silently. If your application has multiple supporting JavaScript files, you can import them importScripts() method which takes file name(s) as argument separated by comma as follows - importScripts("he1per.js", "anotherHe1per.js"); Once the Web Worker is spawned, communication between web worker and its parent page is done using the postMessage() method. Depending on your browser/version, postMessage() can accept either a string or JSON object as its single argument. Message passed by Web Worker is accessed using onmessage event in the main page. Now let us write our bigLoop example using Web Worker. Below is the main page (hello.htm) which will spawn a web worker to execute the loop and to return the final value of variablej -
  • 5. < ! DOCTYPE HTML > <html> <head> < title>Big for loop</title> <script> var worker new Worker( 'bigLoop.js ' ) ; worker.onmessage = function (event alert ( "Completed event . data + "iterations" function sayHe110 alert ("Hello sir. . "); < / script > </head> <body> <input type ="button" onclick="sayHe110()" value=""> </body> </html>
  • 6. Stopping Web Workers Web Workers don't stop by themselves but the page that started them can stop them by calling terminate() method. worker . terminate(); A terminated Web Worker will no longer respond to messages or perform any additional computations. You cannot restart a worker; instead, you can create a new worker using the same URL. Handling Errors The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console. With error handling code, above example would become as following -
  • 7. A terminated Web Worker will no longer respond to messages or perform any additional computations. You cannot restart a worker; instead, you can create a new worker using the same URL. Handling Errors The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console. With error handling code, above example would become as following -
  • 8. < ! DOCTYPE HTML > <html> <head> <tit1e>Big for loop</title> <script> var worker new Worker( 'bigLoop.js ' ) ; worker . onmessage function (event alert ( " Completed event . data + "iterations") worker . onerror function (event) { console. log(event.message, event); function sayHe110 alert("He110 sir") < / script > </head> <body> <input type =" button " onclick="sayHe110()" value="Say Hello"/ > </body> </html>
  • 9. Checking for Browser Support Following is the syntax to detect a Web Worker feature support available in a browser - < ! DOCTYPE HTML > <html> <head> <tit1e>Big for loop</title> <script src=" /js/modernizr-l. 5 . min . js " ></script> <script> function myFunction() { if (modernizr.webworkers) { alert("Congratu1ation! ! you have web workers support. " else alert ("Sorry! ! you do not have web workers support. " </script> </head> <button onclick myFunction()">C1ick me</button> </html> This will produce the following result - CLICK ME
  翻译: