forked from cheton/browserify-css
-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
75 lines (64 loc) · 2.76 KB
/
browser.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
'use strict';
// For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
var styleElementsInsertedAtTop = [];
var insertStyleElement = function(styleElement, options) {
var head = document.head || document.getElementsByTagName('head')[0];
var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
options = options || {};
options.insertAt = options.insertAt || 'bottom';
if (options.insertAt === 'top') {
if (!lastStyleElementInsertedAtTop) {
head.insertBefore(styleElement, head.firstChild);
} else if (lastStyleElementInsertedAtTop.nextSibling) {
head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
} else {
head.appendChild(styleElement);
}
styleElementsInsertedAtTop.push(styleElement);
} else if (options.insertAt === 'bottom') {
head.appendChild(styleElement);
} else {
throw new Error('Invalid value for parameter \'insertAt\'. Must be \'top\' or \'bottom\'.');
}
};
module.exports = {
// Create a <link> tag with optional data attributes
createLink: function(href, attributes) {
var head = document.head || document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = href;
link.rel = 'stylesheet';
for (var key in attributes) {
if ( ! attributes.hasOwnProperty(key)) {
continue;
}
var value = attributes[key];
link.setAttribute('data-' + key, value);
}
head.appendChild(link);
},
// Create a <style> tag with optional data attributes
createStyle: function(cssText, attributes, extraOptions) {
extraOptions = extraOptions || {};
var style = document.createElement('style');
style.type = 'text/css';
for (var key in attributes) {
if ( ! attributes.hasOwnProperty(key)) {
continue;
}
var value = attributes[key];
style.setAttribute('data-' + key, value);
}
if (style.sheet) { // for jsdom and IE9+
style.innerHTML = cssText;
style.sheet.cssText = cssText;
insertStyleElement(style, { insertAt: extraOptions.insertAt });
} else if (style.styleSheet) { // for IE8 and below
insertStyleElement(style, { insertAt: extraOptions.insertAt });
style.styleSheet.cssText = cssText;
} else { // for Chrome, Firefox, and Safari
style.appendChild(document.createTextNode(cssText));
insertStyleElement(style, { insertAt: extraOptions.insertAt });
}
}
};