Menu

Web Workers 6

Timo Kähkönen

Donate Javascript Clipper Project

D. Using Web Workers with Javascript Clipper 6

Javascript Clipper is Web Worker compatible as of version 5.0.2.2.

Web workers is a new technology, that allows browser to run resource expensive tasks in background without affecting to the performance of the main page.

The downside of Web Workers is that certain features are not available: eg. window and document, which means that you cannot manipulate DOM eg. draw on canvas inside Worker task. The other downside is that you have to find a fallback solution for users that are using still older browsers that are not Web Worker capable.

Clipper can be used to handle thousands of polygons with thousands of vertices. In these cases, the browser is very likely to hang. To avoid these problems, the answer is Web Workers.

A Full code example of using Web Workers

Below is an example of drawing complex SVG using Web Workers. The program draws bars, that are randomly colored and sized. The task may take even few seconds, when the count of bars is over 10,000. Using Workers the main page remains responsive.

The example consists of two files: worker_main.html and worker_task.js.

Worker_main.html has the user interface and the functions related to these. Buttons are used to start and stop Web Worker and send drawing commands to worker_task.js.

Worker_task.js consists only of Javascript. Clipper library (clipper.js) is imported at the top of this file. Worker_task.js listens messages that are coming from worker_main.html and starts drawing tasks, generates SVG image source and sends it as a string back to the main page, which renders the image on the screen.

The timer indicates how long the different areas of the task took time. The areas are:

1) transfering the drawing command from main page to the worker
2) drawing SVG source
3) transfering SVG source string from worker to the main page
4) rendering SVG image

To run this example, please save both worker_main.html and worker_task.js below to your hard drive and navigate to worker_main.html. Press buttons on the page and see the results.

See the Worker example in action.


Screenshot of the Web Workers example:


Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.