index.js
1.92 KB
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
var containers = []; // will store container HTMLElement references
var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement}
var usage = 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).';
function insertCss(css, options) {
options = options || {};
if (css === undefined) {
throw new Error(usage);
}
var position = options.prepend === true ? 'prepend' : 'append';
var container = options.container !== undefined ? options.container : document.querySelector('head');
var containerId = containers.indexOf(container);
// first time we see this container, create the necessary entries
if (containerId === -1) {
containerId = containers.push(container) - 1;
styleElements[containerId] = {};
}
// try to get the correponding container + position styleElement, create it otherwise
var styleElement;
if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) {
styleElement = styleElements[containerId][position];
} else {
styleElement = styleElements[containerId][position] = createStyleElement();
if (position === 'prepend') {
container.insertBefore(styleElement, container.childNodes[0]);
} else {
container.appendChild(styleElement);
}
}
// strip potential UTF-8 BOM if css was read from a file
if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); }
// actually add the stylesheet
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText += css
} else {
styleElement.textContent += css;
}
return styleElement;
};
function createStyleElement() {
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
return styleElement;
}
module.exports = insertCss;
module.exports.insertCss = insertCss;