-
Notifications
You must be signed in to change notification settings - Fork 7
/
addStyles.js
40 lines (34 loc) · 1.19 KB
/
addStyles.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
function insertStyleElement(styleElement) {
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(styleElement);
}
function appendStyleContent(styleElement, content) {
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = content;
} else {
while (styleElement.firstChild) {
styleElement.removeChild(styleElement.firstChild);
}
styleElement.appendChild(document.createTextNode(content));
}
}
function createStyleElement(css, id) {
var styleElement = document.querySelector('[data-src="' + id + '"]') || document.createElement('style');
if (!styleElement.parentNode) {
styleElement.setAttribute('type', 'text/css');
styleElement.setAttribute('data-src', id);
styleElement.setAttribute('data-tpa-style', '');
appendStyleContent(styleElement, css);
insertStyleElement(styleElement);
} else {
styleElement.originalTemplate = css;
styleElement.setAttribute('hot-reloaded', 'true');
}
return styleElement;
}
export function addStyles(css, id) {
if (typeof document !== 'object') {
throw new Error('The tpa-style-inject cannot be used in a non-browser environment');
}
createStyleElement(css, id);
}