Skip to content

Commit e7ee263

Browse files
Update HTML to DOM parser to detect environment (browser vs node)
- In node/server, use `htmlparser2` and `domhandler` - In browser/client, use the DOM API that's already provided - Use `DOMParser` but fallback to `innerHTML` - https://developer.mozilla.org/en-US/docs/Web/API/DOMParser - Making this distinction will allow the build to be optimized
1 parent 26213ba commit e7ee263

File tree

1 file changed

+47
-20
lines changed

1 file changed

+47
-20
lines changed

lib/html-to-dom.js

Lines changed: 47 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,53 @@
11
'use strict';
22

33
/**
4-
* Module dependencies.
4+
* Detect environment.
55
*/
6-
var Parser = require('htmlparser2/lib/Parser');
7-
var DomHandler = require('domhandler');
86

9-
/**
10-
* Parse HTML string into DOM nodes.
11-
* This is the same method as `require('htmlparser2').parseDOM`.
12-
*
13-
* @param {String} html - The HTML.
14-
* @param {Object} options - The parser options.
15-
* @return {Object} - The DOM nodes.
16-
*/
17-
function parseDOM(html, options) {
18-
var handler = new DomHandler(options);
19-
new Parser(handler, options).end(html);
20-
return handler.dom;
21-
}
7+
/** Browser. */
8+
if (typeof window !== 'undefined' && this === window) {
9+
var formatDOM = require('./html-to-dom-client');
2210

23-
/**
24-
* Export HTML to DOM helper.
25-
*/
26-
module.exports = parseDOM;
11+
/**
12+
* Parse HTML string to DOM nodes.
13+
* This uses the browser DOM API.
14+
*
15+
* @param {String} html - The HTML.
16+
* @return {Object} - The DOM nodes.
17+
*/
18+
module.exports = function(html) {
19+
// `DOMParser` can parse full HTML
20+
// https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
21+
if (window.DOMParser) {
22+
var parser = new window.DOMParser();
23+
var doc = parser.parseFromString(html, 'text/html');
24+
return formatDOM(doc.childNodes);
25+
26+
// otherwise, use `innerHTML`
27+
// but this will strip out tags like <html> and <body>
28+
} else {
29+
var root = document.createElement('div');
30+
root.innerHTML = html;
31+
return formatDOM(root.childNodes);
32+
}
33+
};
34+
35+
/** Node. */
36+
} else {
37+
var Parser = require('htmlparser2/lib/Parser');
38+
var DomHandler = require('domhandler');
39+
40+
/**
41+
* Parse HTML string to DOM nodes.
42+
* This is the same method as `require('htmlparser2').parseDOM`.
43+
*
44+
* @param {String} html - The HTML.
45+
* @param {Object} options - The parser options.
46+
* @return {Object} - The DOM nodes.
47+
*/
48+
module.exports = function(html, options) {
49+
var handler = new DomHandler(options);
50+
new Parser(handler, options).end(html);
51+
return handler.dom;
52+
};
53+
}

0 commit comments

Comments
 (0)