-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
inject-css.js
68 lines (58 loc) · 1.88 KB
/
inject-css.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
/** @type {HTMLElement[]} */
var containers = [];
/** @type {{prepend:HTMLStyleElement,append:HTMLStyleElement}[]} */
var styleTags = [];
/**
* @param {string} css
* @param {object} options
* @param {boolean} [options.prepend]
* @param {boolean} [options.singleTag]
* @param {string} [options.container]
* @param {Record<string,string>} [options.attributes]
* @returns {void}
*/
export default function (css, options) {
if (!css || typeof document === "undefined") return;
var position = options.prepend === true ? "prepend" : "append";
var singleTag = options.singleTag === true;
var container =
typeof options.container === "string"
? document.querySelector(options.container)
: document.getElementsByTagName("head")[0];
function createStyleTag() {
var styleTag = document.createElement("style");
styleTag.setAttribute("type", "text/css");
if (options.attributes) {
var k = Object.keys(options.attributes);
for (var i = 0; i < k.length; i++) {
styleTag.setAttribute(k[i], options.attributes[k[i]]);
}
}
var pos = position === "prepend" ? "afterbegin" : "beforeend";
container.insertAdjacentElement(pos, styleTag);
return styleTag;
}
/** @type {HTMLStyleElement} */
var styleTag;
if (singleTag) {
var id = containers.indexOf(container);
if (id === -1) {
id = containers.push(container) - 1;
styleTags[id] = {};
}
if (styleTags[id] && styleTags[id][position]) {
styleTag = styleTags[id][position];
} else {
styleTag = styleTags[id][position] = createStyleTag();
}
} else {
styleTag = createStyleTag();
}
// strip potential UTF-8 BOM if css was read from a file
if (css.charCodeAt(0) === 0xfeff) css = css.substring(1);
if (styleTag.styleSheet) {
styleTag.styleSheet.cssText += css;
} else {
styleTag.appendChild(document.createTextNode(css));
}
}