What's web worker for? OK, read it docs to get full details idea. Or just a quick intro to Web worker.
Web worker, open another thread in the background sprated from main thread. You can just think Web worker is a async function ...
OK, so what does Web worker good for? Improve the profermence! Imaging There is some code which need to handle image transform, if you put the whole thing in the main thread, it'll re Ally jank! It freaze your browser for second and it has a poor profermence.
Instead, you can put an image transform code into a web worker and let it help you to handle the heavy code in the background.
To use web worker, only need to do things:
1. Register a web worker.
You need to create a ' worker.js ', the name it whatever you want.
var New Worker (' scripts/worker.js ');
The code should is run in early stage, or let sya idle stage.
2. communiate between Web Worker file and your component file by using: ' PostMessage ' and <worker>.onmessage:
//your componentfunctionmanipulateimage (type) {varA, B, G, I, ImageData, J, length, Pixel, r, ref; ImageData= Ctx.getimagedata (0, 0, Canvas.width, canvas.height); Togglebuttonsabledness (); imageworker.postmessage ({ ' imageData ': imageData, ' type ' : type}); Imageworker. onmessage =function(e) {togglebuttonsabledness (); varImage =E.data; if(image)returnCtx.putimagedata (e.data, 0, 0); Console.log ("No manipulated image returned.")} imageworker. onerror =function(Error) {functionworkerexception (message) { This. Name = "Workerexception"; This. Message =message; }; Throw NewWorkerexception (' Worker error. ')); }; };
//require some JS files on the topImportscripts (' Imagemanips-improved.js ');//Listen for the message This. OnMessage =function(e) {varImageData =E.data.imagedata; varType =E.data.type; Try{length= IMAGEDATA.DATA.LENGTH/4; varManipulatepixel =Getmanipfunc (type); for(i = j = 0, ref = length; 0 <= ref. J <= Ref:j >= ref; i = 0 <= ref? ++J:--j) {R= imagedata.data[i * 4 + 0]; G= Imagedata.data[i * 4 + 1]; b= Imagedata.data[i * 4 + 2]; A= Imagedata.data[i * 4 + 3]; Pixel=Manipulatepixel (R, G, B, a); Imagedata.data[i* 4 + 0] = pixel[0]; Imagedata.data[i* 4 + 1] = pixel[1]; Imagedata.data[i* 4 + 2] = pixel[2]; Imagedata.data[i* 4 + 3] = Pixel[3]; } //Send Message back to the component postMessage (imageData); } Catch(e) {functionmanipulationexception (message) { This. Name = "Manipulationexception"; This. Message =message; }; Throw NewManipulationexception (' Image manipulation error '); postMessage (undefined); }}
[Web Worker] Introduce to Web Worker