forked from rehypejs/rehype-minify
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (68 loc) · 1.82 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* rehype plugin to move CSS `<link>`s to the head.
*
* ## What is this?
*
* This package is a plugin that can improve performance by *decreasing* the
* time to
* [first render](https://developer.yahoo.com/performance/rules.html#css_top).
*
* ## When should I use this?
*
* You can use this plugin when you want to improve the speed of HTML documents.
*
* ## API
*
* ### `unified().use(rehypeCssToTop)`
*
* Move CSS `<link>`s to the head.
* There are no options.
*
* @example
* {"processor": {"fragment": false}}
*
* <!doctype html><html><head></head><body><link rel="stylesheet" href="index.css"></body></html>
*/
import {visit} from 'unist-util-visit'
import {isCssLink} from 'hast-util-is-css-link'
/**
* @typedef {import('hast').Root} Root
* @typedef {import('hast').Element} Element
*/
/**
* Move CSS `<link>` elements to the `<head>`.
*
* This can *decrease* the time to
* [first render](https://developer.yahoo.com/performance/rules.html#css_top)
*
* @type {import('unified').Plugin<Array<void>, Root>}
*/
export default function rehypeCssToTop() {
return (tree) => {
/** @type {Array<[Root|Element, Element]>} */
const matches = []
/** @type {Element|undefined} */
let head
visit(tree, 'element', (node, _, parent) => {
const ancestor = /** @type {Root|Element} */ (parent)
if (node.tagName === 'head') {
head = node
}
if (
isCssLink(node) &&
(ancestor.type !== 'element' || ancestor.tagName !== 'head')
) {
matches.push([ancestor, node])
}
})
if (head) {
let index = -1
while (++index < matches.length) {
const match = matches[index]
const siblings = match[0].children
siblings.splice(siblings.indexOf(match[1]), 1)
head.children.push(match[1])
}
}
}
}