react screenshot is too slow,i want to use worker, but i meet some question

51 Views Asked by At

i want to use domtoimage in react to get screenshot, but it too slow when the dom is large, and it can Causing page lag

so i want to use worker, but i also meet some problem, who can help me? this is my code :

importScripts('dist/dom-to-image.min.js')
self.importScripts('dist/dom-to-image.min.js')
const workerCode = () => {
  self.onmessage = function (e) {
    console.log(e)

    const data = e.data

    domtoimage.toPng(data).then((res) => self.postMessage(res))
  }
}

let code = workerCode.toString()
code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'))
const blob = new Blob([code], { type: 'application/javascript' })
const workerScriptURL = URL.createObjectURL(blob)

export default workerScriptURL

the question is :'importScripts' is not defined and 'domtoimage' is not defined

who can solve this capture too slow problem or worker problem

i use typeof, but it alse have error

1

There are 1 best solutions below

2
Fazle Rabbi Ador On

i think this should work

// In your main React code:
const workerScriptURL = URL.createObjectURL(new Blob([`
  const domtoimage = null; // Initialize as null for later import

  self.onmessage = function (e) {
    console.log(e);

    if (!domtoimage) { // Import if not already done
      importScripts('dist/dom-to-image.min.js');
      domtoimage = window.domtoimage; // Use window.domtoimage inside worker
    }

    const data = e.data;

    domtoimage.toPng(data).then((res) => self.postMessage(res));
  };
`], { type: 'application/javascript' }));

// Create and use the worker...

Add importScripts('dist/dom-to-image.min.js') inside the worker's workerCode function.