问题
I have an HTML table with different columns and rows. The table can be edited inline by a user. When a user edits the table, I calculate some sums on the rows of table.
The function that calculates the sums was in the main script and took a lot of time making the browser unresponsive. To solve this performance issue, I have created a web worker in JavaScript to calculate the sums on the table.
The problem is that the web worker cannot access the DOM. I'm looking for a way to pass a jQuery object table to the web worker.
If I try to pass the jQuery object I receive an error:
Uncaught DataCloneError: Failed to execute 'postMessage' on 'Worker': An object could not be cloned.
How I can pass the table to the Web Worker?
Thank you
[EDIT adding some further information ]
The sum take a long time because the table has a lot of rows and calculate different sums (total, subtotal,etc). The values to sum are stored in table (so worker need to access to table to perform the calculation).
My idea is to pass DOM object to worker to calculate sums. After calculation, worker return the sums to main thread in order to update values in the DOM.
回答1:
In short you cannot pass a DOM element to a worker. Only data, typically as strings, can be passed to webworkers not objects. You should extract your data from your table, wrap it up in an object, turn your object into json, send the json to the worker, process it and return some json back to the main thread.
回答2:
you could do this remember you can pass string or numbers as objects. then loop through the number and keep receiving strings. then use table.innerHTML to change it.
const row = '<tr></tr>';
const worker = new Worker('worker.js');
worker.postmessage({'row': row});
worker.onmessage = function(e){
const result = e.data.result;
//do something
};
worker.terminate();
来源:https://stackoverflow.com/questions/29947630/javascript-how-can-i-pass-a-jquery-object-table-to-a-web-worker