1 |
|
2 | var containers = [];
|
3 |
|
4 | var styleElements = [];
|
5 |
|
6 | var usage = 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).';
|
7 |
|
8 | function createStyleElement() {
|
9 | var styleElement = document.createElement('style');
|
10 | styleElement.setAttribute('type', 'text/css');
|
11 | return styleElement;
|
12 | }
|
13 |
|
14 |
|
15 | function insertCss(css, options) {
|
16 | options = options || {};
|
17 |
|
18 | if (css === undefined) {
|
19 | throw new Error(usage);
|
20 | }
|
21 |
|
22 | var position = options.prepend === true ? 'prepend' : 'append';
|
23 | var container = options.container !== undefined ? options.container : document.querySelector('head');
|
24 | var containerId = containers.indexOf(container);
|
25 |
|
26 | if (containerId === -1) {
|
27 | containerId = containers.push(container) - 1;
|
28 | styleElements[containerId] = {};
|
29 | }
|
30 |
|
31 |
|
32 | var styleElement;
|
33 |
|
34 | if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) {
|
35 | styleElement = styleElements[containerId][position];
|
36 | } else {
|
37 | styleElement = styleElements[containerId][position] = createStyleElement();
|
38 |
|
39 | if (position === 'prepend') {
|
40 | container.insertBefore(styleElement, container.childNodes[0]);
|
41 | } else {
|
42 | container.appendChild(styleElement);
|
43 | }
|
44 | }
|
45 |
|
46 |
|
47 | if (css.charCodeAt(0) === 0xfeff) {
|
48 | css = css.substr(1, css.length);
|
49 | }
|
50 |
|
51 |
|
52 | if (styleElement.styleSheet) {
|
53 | styleElement.styleSheet.cssText += css;
|
54 | } else {
|
55 | styleElement.textContent += css;
|
56 | }
|
57 |
|
58 | return styleElement;
|
59 | }
|
60 |
|
61 | export default insertCss; |
\ | No newline at end of file |