-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
105 lines (81 loc) · 2.14 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* Module dependencies.
*/
var callasync = require('callasync');
/**
* Expose `loadcss`.
*/
module.exports = loadcss;
/**
* Loads and inserts stylesheets with the specified `href` and `options`;
*
* @param {Array|string} href
* @param {Object|Function} [options]
* @param {DOMElement} [options.before]
* @param {string} [options.media]
* @param {Function} [options.complete]
*/
function loadcss(href, options) {
options || (options = {});
if (({}).toString.call(options) === '[object Function]') {
options = { complete: options };
}
var doc = document;
var sheets = doc.styleSheets;
var hrefs = ({}).toString.call(href) === '[object Array]' ? href : [href];
var media = options.media ? options.media : 'all';
var oncomplete = options.complete || function () {};
var links = [];
var before;
if (options.before) {
before = options.before;
} else {
var refs = (doc.body || doc.getElementsByTagName('head')[0]).childNodes;
before = refs[refs.length - 1];
}
function onready(callback) {
if (doc.body){
return callback();
}
callasync(function () {
onready(callback);
});
}
function onloaded() {
var loaded = 0;
var index = -1;
var length = links.length;
while (++index < length) {
if (exists(links[index].href) && ++loaded === length) {
return oncomplete(links);
}
}
callasync(onloaded);
}
function exists(href) {
var index = -1;
var length = sheets.length;
while (++index < length) {
if (sheets[index].href === null || sheets[index].href.length === 0) {
continue;
}
if (sheets[index].href === href) {
return true;
}
}
}
onready(function () {
var index = -1;
var length = hrefs.length;
var referenceNode = options.before ? before : before.nextSibling;
while (++index < length) {
links[index] = doc.createElement('link');
links[index].rel = 'stylesheet';
links[index].href = hrefs[index];
links[index].media = media;
before.parentNode.insertBefore(links[index], referenceNode);
}
callasync(onloaded);
});
return links;
}