OffScreenCanvas, Workers and performance!
Improving performance is vital when doing any kind of rendering on the client side.
With the help of the
OffscreenCanvas API we’re able to make the rendering of our canvas in a Worker which means that even if our page is busy the render of the canvas will be fine.
(Workers are like threads but for web they run in the background thread, more info on workers here.)
More information about the
OffscreenCanvas and compatibility are available on MDN:
Here is a simple demonstration that I created: https://offscreencanvas-demo.glitch.me/
The page is separated into two part:
- The top one is used to put some pressure on the selected canvas
- And the bottom one is used the visualisation part, with the canvases.
When clicking the button to simulate a heavy process on:
Canvas A, we can observe a few things:
- The page becomes slightly unresponsive, and feels laggy.
- The hover effect on the button are freezing.
- We can see that Canvas B is still working fine.
- We might even get a message from the browser saying that the page is unresponsive, and recommending us to close it.
Canvas B, we can observe:
- Canvas B becomes slow but doesn’t impact the rest of the page
- The hover effect works
- The page feels responsive, and smooth
But Canvas B, is rendered using the OffscreenCanvas API thus the rendering process is done in a Worker so that if there is a heavy task it is absorbed by the worker itself and not
Most of the magic happens in the “worker.js” file:
The code bellow, is used to get the worker as an
Then we initialise a worker with the worker.js script.
And finally we send the
OffScreenCanvas using the worker
And here we have the worker.js,
To get a better view of how everything works, I’d recommend checking the source code witch is on Glitch here: https://glitch.com/edit/#!/offscreencanvas-demo
Feel free to remix ✨!
As always thanks a lot for reading my blog post and see you soon!