Vitaliy Tarnavskyy Jun 26, 2013 Using Web workers in Javascript.

Slides:



Advertisements
Similar presentations
JavaScript is a client-side scripting language. Programs run in the web browser on the client's computer. (PHP, in contrast, is a server-side scripting.
Advertisements

Introducing JavaScript
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
HTML5 Applications with ASP.NET Web Forms Stephen Walther Superexpert.com
The Web Warrior Guide to Web Design Technologies
An Evaluation of the Google Chrome Extension Security Architecture
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
Javascript Document Object Model. How to use JavaScript  JavaScript can be embedded into your html pages in a couple of ways  in elements in both and.
JavaScript, Third Edition
Chapter 9 Introduction to the Document Object Model (DOM) JavaScript, Third Edition.
CHAPTER 28 INTEGRATING WEB WORKERS. LEARNING OBJECTIVES How a Web worker is essentially a JavaScript routine that performs concurrent processing within.
Canvas, SVG, Workers Doncho Minkov Telerik Corporation
Presented by…. Group 2 1. Programming language 2Introduction.
Martin Kruliš by Martin Kruliš (v1.0)1.
4.1 JavaScript Introduction
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
SUNY Polytechnic Institute CS 490 – Web Design, AJAX, jQueryAngularJS AngularJS is a client-side JavaScript Framework for adding interactivity to HTML.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
JQuery 10/21. Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions.
Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JavaScript is a client-side scripting language. Programs run in the web browser on the client's computer. (PHP, in contrast, is a server-side scripting.
CSE 190: Internet E-Commerce Lecture 5. Exam Material Lectures 1-4 (Presentation Tier) –3-tier architecture –HTML –Style sheets –Javascript –DOM –HTTP.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
WEB WORKERS 1 Amitesh Madhur (Exceptional Performance, Bangalore)
Chapter 34 Java Technology for Active Web Documents methods used to provide continuous Web updates to browser – Server push – Active documents.
JavaScript, Fourth Edition
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects.
1 JavaScript in Context. Server-Side Programming.
Tutorial 10 Programming with JavaScript
Done by: Hanadi Muhsen1 Tutorial 1.  Learn the history of JavaScript  Create a script element  Write text to a Web page with JavaScript  Understand.
HTML5, part III – API, … Štěpán Developer Evangelist Microsoft, Czech Republic.
XP Tutorial 6 New Perspectives on JavaScript, Comprehensive1 Working with Windows and Frames Enhancing a Web Site with Interactive Windows.
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
Topic 7 Temporal Control. 2Chapter 25 - Temporal ControlOutline Goals and Objectives Goals and Objectives Introduction Introduction Timeline Animation.
Modified from Moseley ’s sli desWeb Applications Development. Lecture 3 Slide 1 Lecture 3: Dynamic Web Pages – Introduction to JavaScript Instructor: Dr.
JavaScript, Fourth Edition Chapter 4 Manipulating the Browser Object Model.
ASP.NET (Active Server Page) SNU OOPSLA Lab. October 2005.
1 JavaScript in Context. Server-Side Programming.
1 Isolating Web Programs in Modern Browser Architectures CS6204: Cloud Environment Spring 2011.
Creating Animations, Working with Graphics, and Accessing Data Lesson 9.
Threads. Readings r Silberschatz et al : Chapter 4.
Node.Js 1. 2 Contents About Node.Js Web requirement latest trends Introduction Simple web server creation in Node.Js Dynamic Web pages Dynamic web page.
CHAPTER 10 ERROR HANDLING & DEBUGGING JavaScript can be hard to learn. Everyone makes mistakes when writing it.
Adding Javascript How to include javascript in a webpage.
COSC 2328 – Web Programming.  PHP is a server scripting language  It’s widely-used and free  It’s an alternative to Microsoft’s ASP and Ruby  PHP.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
CGS 3066: Web Programming and Design Spring 2016 Introduction to JavaScript.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
Introduction to ASP.NET development. Background ASP released in 1996 ASP supported for a minimum 10 years from Windows 8 release ASP.Net 1.0 released.
By Collin Donaldson. Hacking is only legal under the following circumstances: 1.You hack (penetration test) a device/network you own. 2.You gain explicit,
Martin Kruliš by Martin Kruliš (v1.1)1.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
CGS 3066: Web Programming and Design Spring 2017
>> Introduction to JavaScript
Javascript and Dynamic Web Pages: Client Side Processing
CSE 154 Lecture 11: AJAx.
JavaScript: Good Practices
Tutorial 10 Programming with JavaScript
Data Virtualization Tutorial… CORS and CIS
CSE 154 Lecture 11: AJAx.
Web Systems Development (CSC-215)
CSE 154 Lecture 22: AJAX.
Building responsive apps and sites with HTML5 web workers
JavaScript & jQuery AJAX.
Lecture 12: The Fetch Api and AJAx
Introduction to JavaScript
Presentation transcript:

Vitaliy Tarnavskyy Jun 26, 2013 Using Web workers in Javascript

Agenda Before the workers: history Simple examples Accessibility and environment Workers features Shared workers Usage tips Examples

Multi-threading?

Before the Workers Javascript historical limitation All execution process remains inside a unique thread Main UI thread In charge of handling all the visual elements and associated tasks: drawing, refreshing, animating, user inputs events

Annoying popup

Overloading the thread Browser protection mechanism Alerts users when a long-running suspect script occurs Mechanism can’t tell the difference Between a script not written correctly and a script that just needs more time

Solve concurrency problem Simulating with setTimeout(), setInterval() XMLHttpRequest DOM Events

DOM Events concurrency illusion

What is Web Worker?

What are Web Workers? Scripts running in background Heavy Weight Scripts

Simple example Initializing the worker var worker = new Worker('doWork.js'); worker.addEventListener('message', function(e) { console.log('Worker said: ', e.data); }, false); /* worker.onmessage = … */ worker.postMessage('Hello World');

Simple example Creating the worker self.addEventListener('message', function(e) { self.postMessage(e.data); }, false); Result Worker said: Hello World!

Passing JSON … function sayHI() { worker.postMessage({'cmd': 'start', 'msg': 'Hi'}); } … switch (data.cmd) { case 'start': self.postMessage('WORKER STARTED: ' + data.msg); break; } …

Passing Javascript objects Structured Clone Algorithm is used Can pass RegExp objects Blob, File, and FileList objects ImageData objects Circular references Limitations Error objects, Functions, or DOM objects Property descriptors, setters, and getters are not saved Prototype chain is not copied

Passing Transferrable objects Data is transferred from one context to another Pass-by-reference if you're from the C/C++ world worker.postMessage(arrayBuffer, [arrayBuffer]);

Tips Check on existence if (!!window.Worker) Stop the worker outside worker.terminate() Stop the worker inside self.close()

Browser support Can I use:

Browser support Modernizr: Modernizr.load({ test: Modernizr.webworkers, yep: 'magic_fast_worker.js', nope: 'slow_stupid_script.js' });

Environment: scope This and Self reference the global scope onmessage = function(e) { this.postMessage(e.data); }); addEventListener('message', function(e) { postMessage(e.data); }, false);

Available features The navigator object The location object (read-only) XMLHttpRequest setTimeout(), setInterval() The Application Cache Importing external scripts Spawning other web workers JavaScript objects such as Object, Array, Date, Math, String

No access to The DOM (it's not thread-safe) The window object The document object The parent object

DOM and Workers

Loading External Scripts Import importScripts(); importScripts('foo.js'); importScripts('foo.js', 'bar.js'); May be downloaded in any order Will be executed in the pass order

Sub-workers Worker var num_workers = 10; var items_per_worker = ; var result = 0; var pending_workers = num_workers; for (var i = 0; i < num_workers; i += 1) { var worker = new Worker('core1.js'); worker.postMessage(i * items_per_worker); worker.postMessage((i+1) * items_per_worker); worker.onmessage = storeResult; }

Sub-workers Worker function storeResult(event) { result += 1*event.data; pending_workers -= 1; if (pending_workers <= 0) console.log(result); } Sub-worker onmessage = function (e) { postMessage(e.data); }

Sub-workers limitations Hosting Must be hosted within the same origin as the parent page URIs within sub-workers Are resolved relative to their parent worker's location (as opposed to the main page) Separate processes for each worker Be cautious about hogging too many of the user's system resources

Inline workers Creating the worker var blob = new Blob(["onmessage = function(e) { postMessage('msg from worker'); } "]); var blobURL = window.URL.createObjectURL(blob); var worker = new Worker(blobURL);

Inline workers Release a Blob URLs window.URL.revokeObjectURL(blobURL); Chrome page with Blobs chrome://blob-internals/ blob:blobinternal%3A///85c562e6-9c76-4bff-a165… Type: data Length: 59

Inline workers self.onmessage = function(e) { self.postMessage('msg from worker'); }; var blob = new Blob([ document.querySelector('#worker1').textContent ]);

Inline workers Work only with absolute URIs var blob = new Blob(["onmessage = function(e) { importScripts('xxx.js'); } "]); // Uncaught Error: SyntaxError: DOM Exception 12 Solution - pass URL into worker worker.postMessage({url: document.location});

Shared workers One worker for many windows // Window 1 var aSharedWorker = new SharedWorker("SharedWorker.js", "Worker1"); // Window 2 var aSharedWorker = new SharedWorker("SharedWorker.js", "Worker2");

Shared workers Scope of Shared Workers Window 1 creates a shared worker Window 2 connects to it Window 1 is closed Window 2 is still connected The shared worker thread remains Even though Window 2 didn't originally create it

Shared workers Initializing the worker var worker = new SharedWorker("SharedWorker.js"); function onMsg (e) { console.log('Worker said: ', e.data); } worker.port.addEventListener('message', onMsg, false); worker.port.start(); worker.port.postMessage("Hello World");

Shared workers Creating the worker var i = 0; onconnect = function (evt) { evt.ports[0].onmessage = function (e) { OnControllerMessage(e, port); } function OnControllerMessage(e, port) { i++; port.postMessage(e.data + i); }

Shared workers Another way var i = 0; onconnect = function (evt) { evt.ports[0].onmessage = OnControllerMessage; } function OnControllerMessage(e) { i++; e.target.postMessage(e.data + i); }

Shared workers Results Window 1 call – Hello World 1 Window 2 call – Hello World 2 Window 1 call – Hello World 3

Browser support Can I use:

Error handling Setting up onerror handler function onError(e) { console.log( 'ERROR: Line ' + e.lineno + ' in ' + e.filename, + ': ' + e.message ); } worker.addEventListener('error', onError, false);

Debugging: IE 10

Debugging: Chrome

Debugging: console No console.log() in worker Uncaught ReferenceError: console is not defined WorkerConsole.js

Tips Live until killed Since they aren’t automatically garbage collected, it’s up to you to control their state Won’t run locally Due to Google Chrome's security restrictions, workers will not run locally (e.g. from file://) Must be same scheme E.g. https: page cannot start worker scripts that begin with http: URLs.

Where to use Image processing Big amount of data Background text analysis Concurrent requests against a local database Prefetching and/or caching data Background I/O or polling of web services Image filtering in

Pay attention The initializing time and the communication time The memory cost of using several Workers The dependency of the code blocks

Summary Use web workers or at least take a look into that, because that’s interesting!

Questions?

Sources The Basics of Web Workers By Eric BidelmanEric Bidelman HTML Living Standard / Web Workers Introduction to HTML5 Web Workers: The JavaScript Multi- threading Approach A Deeper Look at HTML 5 Web Workers An Introduction to HTML 5 Web Workers

Thanks