问题
I know that workers can't manipulate the document directly, but how about the DOM API methods? Where did they go?!
For example if I make a request that receives a HTML fragment, what I'm supposed to do if need just to parse it in order to retrieve some data from a specific node?!
There's absolutely no way to work with virtual DOM on web workers?!
回答1:
Support in browsers
DOMParser
or document.implementation
are usually used to parse HTML to DOM in browsers. Neither is available in worker context.
In Firefox, this is not possible because someone just went full retard and decided there will be only one DOM parser instance for all threads. See this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=677123
In google chrome it doesn't work either.
Workaround - external library
That's right, since browser developers didn't realize DOM and XML parsing will be one of main uses of WebWorkers, we'll have to fall back to external library. The best bet seems to be JSDOM, but you'll need to figure out how to browserify it.
Here's my failed attempt with DOMParser
, I keep it for future experiments on this topic: https://jsfiddle.net/svaqb2wn/2/
回答2:
I just made a library that solves this exact problem. It is based on the cycle architecture, it is still WIP but you can find the source here.
http://github.com/aronallen/-cycle-sandbox/
回答3:
You can use one of the DOM implementations running in a Web Worker:
- Domino
- JSDOM
- XMLDOM
- WorkerDOM
- Via.js
回答4:
At first you might think the proper way to go about parsing XML is XMLHttpRequest
and in 9 out of 10 cases you would be right. However, in the current web worker spec we don't have access to XMLHttpRequest
. An alternative is to use one of a few popular XML parsing libraries:
https://github.com/isaacs/sax-js
http://xmljs.sourceforge.net/index.html or https://www.npmjs.com/package/xmljs
HTML is just XML, so you can parse your data in this manner. An example using xmljs from npmjs above:
var XmlParser = require("xmljs");
var fs = require("fs");
var p = new XmlParser({ strict: true });
var xml = fs.readFileSync("./SOAP1.xml"); // XML in the examples direct
var xmlNode = p.parseString(xml, function(err, xmlNode) {
if(err) {
console.error(err);
return;
}
var nodes = xmlNode.path(["Envelope", "Body", "GetstockpriceResponse", "Price"], true);
console.log(nodes.map(function(n) { return n.text; }));
});
来源:https://stackoverflow.com/questions/33641622/dom-manipulation-inside-web-worker