17. Web Workers

About this Tutorial

Objectives

Delegates will learn to develop applications using HTML5/CSS3 and JS. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial HTML5 Web Applications
  • Develop Websites that may use web sockets, animations and geolocation

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of HTML/CSS and JavaScript will also find the content beneficial.

Prerequisites

No previous experience in web programming is required. But any experience you do have in programming will help. Also no experience in browser IDE’s is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview

Estimated Time – 1 Hour

  1. Key Concepts
    • HTML5 Web Workers bring background processing capabilities to web applications
      • Run on separate threads, so JavaScript apps using HTML5 Web Workers can take advantage of multi-core CPUs
      • Separating long-running tasks into HTML5 Web Workers also avoids the “slowscript” warnings
        T17P1

Lab 1: Overview of HTML5 Web Workers

Lab 1: Overview of HTML5 Web Workers

wcccccc

  1. Some Restrictions
    • Web Workers are powerful, but there are some things they can’t do
      • When a script is executing inside a Web Worker, it can’t access the web page’s window object (window.document)
      • This means Web Workers don’t have direct access to the web page and the DOM API
      • You overcome this limitation by sending update messages to the main Web page
    • Also, be sensible!
      • Although Web Workers can’t block the browser UI, they can still consume CPU cycles
      • This could make system less responsive
  2. Example Scenario 1
    • You want to create a Web app that has to perform some background number crunching
      • You don’t want those tasks to interfere with the interactivity of the Web page itself
      • Using Web Workers, you can spawn a Web Worker to perform the tasks
      • Typically, you’ll also define an event listener to listen to messages from the Web Worker as they are sent
  3. Example Scenario 2
    • A web app could use Web Workers to listen for news messages broadcast from a back-end server
      • This Web Worker might use Web Sockets or Server-Sent Events to talk to the back-end server
      • Typically, the Web Worker would post messages to the main web page as they are received from the back-end server
  4. How Web Workers Work
    • To use Web Workers in a Web page:
      • Create a Web Worker object, and pass in a JavaScript file to be executed
      • In the page, set up an event listener to process incoming messages and errors posted by the Web Worker
      • To communicate from a Web page to a Web Worker, call postMessage() to pass in the required data
    • To implement a Web Worker:
      • Create a JavaScript file
      • In the JavaScript file, set up an event listener to process incoming messages and errors posted by the Web page
      • To communicate from a Web Worker to a Web page, call postMessage() to pass in the required data
  5. Checking for Support
    • You can check whether your browser supports Web Workers
      function testForWebWorkers() {
      if (typeof(Worker) !== "undefined") {
        alert("Your browser supports Web Workers.");
       }
       else {
        alert("Sorry pal, your browser doesn't support Web Workers.");
       }
      }
Lab
  1. In this lab, you’ll implement a multi-threaded Web application that calculates prime numbers. The user will be able to find all the prime numbers in a specified range. The user will be able to kick off several searches at once, each goes into a different thread (and the user will be able to cancel a search if they want to).
  2. You will be working through the folder labelled initial with all the finished solutions in the folder labelled final for your use if you get stuck at any point.
  3. Understanding the starter project
    • Start Visual Studio and open the initial project for this lab (PrimeNumbersApp.sln)
    • In Solution Explorer, expand the Views/Home folder and open Index.cshtml. This is the home page (and only page) in the Web application. It has the following UI elements, plus a bit of on-load initialization code:
    • View code file.
      • A text box, where the user can enter a number
      • A button named Find Primes
      • A button named Cancel
      • A text area named Result
    • The project also has a helper script file named Utilities.js (located in the Script folder), to determine if a given number is prime.
    • View code file.

Lab 2: Using the HTML5 Web Workers API

Lab 2: Using the HTML5 Web Workers API
  1. Creating Web Workers
    • Web Workers are worker JavaScript object
      • When you create a Worker object, you must specify the URL of the JavaScript file
      • The code in the JavaScript file will run in a separate thread
        var aWorker = new Worker("MyWorker.js");
    • The URL can be relative or absolute
      • If relative, it will assume the same scheme, host, and port as the main page
  2. Setting up Event Handlers
    • Before you tell the Web worker to do anything, you should set up two event handlers on the Web worker:
    • message event
      • Will handle messages posted back from the worker (e.g. results)
        aWorker.addEventListener("message", myMessageHandler, true);
        ...
        function myMessageHandler(e) {
         alert("Worker response data: " + e.data);
        }
    • error event
      • Will handle an errors that occur (e.g. script-loading errors)
        aWorker.addEventListener("error", myErrorHandler, true);
        ...
        function myErrorHandler(e) {
         alert("Error [" + e.filename + ", line " + e.lineno + "] " + e.message);
        }
  3. Communicating with a Web Worker
    • To communicate from a Web page to a Web Worker:
      • Call postMessage() to pass in the required data
    • Example 1
      • Posting a simple string message:
        aWorker.postMessage("Here's some data for the Web Worker to use");
    • Example 2
      • Posting a JSON object (e.g. a person) as a message:
        aWorker.postMessage({ 'name': 'Andy',
                   'age':  21,
                   'welsh': true });
  4. Stopping Web Workers
    • Web Workers don’t stop by themselves, but the page that started them can stop them
      • E.g. to reclaim resources when a Web Worker has notified the Web page that it has finished its tasks
      • E.g. to cancel a long-running task, in response to user intervention
    • To stop a Web Worker:
      • Call terminate() on the Worker object
        aWorker.terminate();
  5. Implementing a Web Worker
    • A Web Worker can listen for incoming messages sent from the Web page:
      • Define an event listener to listen for message events
        addEventListener("message", myWorkerMessageHandler, true);
        ...
        function myWorkerMessageHandler(e) {
         // Access message from main page via e.data.
         // E.g. e.data accesses the whole message object.
         // E.g. e.data.name, e.data.age, e.data.welsh accesses parts of the message object.
        }
    • A Web Worker can communicate back to a Web page:
      • Call postMessage() to pass in the required data
      • You can pass anything (e.g. a string or a JSON object)
        postMessage("Here's some data for the Web page to display");
  6. Loading and Executing Additional JS
    • Web pages import JavaScript files via <script> tags
      • The <script> tags load JS files synchronously, as the page loads
    • However, Web Workers don’t have access to the document object
      • So Web Workers can’t use <script> tags load JS files
      • Instead, they can call the importScripts() function
      • Loads and executes JS files synchronously, into the existing worker
        importScripts("MyHelper1.js", "MyHelper2.js");
  7. Additional Techniques
    • A Web Worker can create sub-workers:
      var subWorker = new Worker("MySubWorker.js");
    • HTML5 Web Workers can’t access the window object, but they can use the JavaScript timing API
      var t = setTimeout(postMessage, 2000, "Delayed message to main page");
  8. Example: Passing String Parameters – Open the demo project in Visual Studio. Run the app, and click the Simple Echo Demo link
    T17P2
  9. Example: Passing Object Parameters – Open the demo project in Visual Studio. Run the app, and click the Object Echo Demo link
    T17P3
Lab
  1. Performing multithreading
    • Handle the click event on the Find Primes button as follows:
      • Kick-off a Web Worker to calculate all the prime numbers between 1 and the number specified in the textbox.
      • View code file.
      • // Update UI controls in readiness for the new worker.
        messageAreaElem.innerHTML = "Starting worker...";
        resultAreaElem.value = "";
        // Create a new worker.
        primesWorker = new Worker("/Scripts/GetPrimeNumbers.js");
        primesWorker.addEventListener("message", onMessage, true);
        primesWorker.addEventListener("error", onError, true);
        // Start the worker, passing a JSON object as a parameter.
        primesWorker.postMessage({
         'lowerNumber': parseInt(lowerNumberElem.value),
         'upperNumber': parseInt(upperNumberElem.value),
         'startTime': new Date()
        });

      • The Web Worker should loop through the number range, and add prime numbers to an array like this:
        var primes = new Array();
        for (var n = lower; n <= upper; n++) {  if (isPrimeNumber(n)) {   // n is a prime number, so add it to the array of prime numbers.   primes.push(n);   ...
      • The Web Worker should post this array back to the main page when done.
        postMessage( { type: "result",
            startTime: startTime,
            endTime: new Date(),
            allPrimes: primes } );
      • The main page should retrieve the data, and display in the text area.
        messageAreaElem.innerHTML = "The worker that started at " + e.data.startTime.toTimeString() + " has ended at " + e.data.endTime.toTimeString();
        resultAreaElem.value = e.data.allPrimes;
    • Run the application and test that it works correctly.
  2. Well done! You have completed the HTML5 course.
    How do I get a certificate of Completion for this course?

    1. Once you have subscribed, TalkIT can monitor some of your activity on the website. But as the tutorials are designed to allow you to work when you want, we do not know exactly when you have finished a course - So just email TalkIT with:
      • The date you have completed all the tutorials in the course
      • Include the title of the course
    2. TalkIT will then send you a certificate of completion for that course

 

Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top