Search code examples
javascriptchart.jsweb-worker

Using Chart.js in Web Worker


I am trying to use Worker for drawing the Chart using Chart.js, as mentioned on the Chart.js page:
https://www.chartjs.org/docs/master/general/performance/
Section: Parallel rendering with web workers (Chrome only)

But in the worker.js file I get an error:

Uncaught ReferenceError: Chart is not defined

I have below code in worker.js:

onmessage = function(event) {
    const {canvas, config} = event.data;
    const chart = new Chart(canvas, config); // Error for Chart 

    canvas.width = 100;
    canvas.height = 100;
    chart.resize();
};

Solution

  • You need to import the library inside your worker's script.

    For this you can use the importScripts() method.

    Also be sure to use the v.3 of the library as v2.x was expecting a DOM HTMLElement, and finally, it seems you need to set a global window variable (set it to self) in your Worker:

    const worker_script = `
      const window = self;
      importScripts("https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta/chart.min.js");
    
      onmessage = function(event) {
        const {canvas, config} = event.data;
        const chart = new Chart(canvas, config); // Error for Chart 
    
        canvas.width = 500;
        canvas.height = 500;
        chart.resize();
      };
    `;
    const worker_url = URL.createObjectURL(new Blob([worker_script], { type: "text/javascript" }));
    
    const worker = new Worker(worker_url);
    const canvas = document.getElementById("canvas").transferControlToOffscreen();
    const config = { type:"line",data:{labels:["January","February","March","April","May","June","July"],datasets:[{label:"My First Dataset",data:[65,59,80,81,56,55,40],fill:false,borderColor:"rgb(75, 192, 192)",lineTension:0.1}]} };
    
    worker.postMessage({ canvas, config }, [canvas]);
    <canvas id="canvas"></canvas>