-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslim.js
79 lines (63 loc) · 1.94 KB
/
slim.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
/* naive version of the css plugin for the slim loader */
module.exports = function(moduleId, config) {
return new CssModule(config.paths[config.bundles[moduleId]]).injectLink();
};
function CssModule(address) {
this.address = address;
}
// timeout in seconds
CssModule.waitTimeout = 60;
// The slim build does not resolve to URLs, so this trick is needed
// to get the url and use it to check if the link was already added
// to the head
CssModule.prototype.getLinkUrl = function() {
var anchor = document.createElement("a");
anchor.href = this.address;
return anchor.href;
};
CssModule.prototype.linkExists = function() {
var styleSheets = document.querySelectorAll('[rel="stylesheet"]');
if (styleSheets != null) {
var href = this.getLinkUrl();
for (var i = 0; i < styleSheets.length; ++i) {
if (href === styleSheets[i].href) {
return true;
}
}
}
return false;
};
CssModule.prototype.injectLink = function() {
if (this._loadPromise) {
return this._loadPromise;
}
if (this.linkExists()) {
this._loadPromise = Promise.resolve("");
return this._loadPromise;
}
// inspired by https://github.com/filamentgroup/loadCSS
var link = (this.link = document.createElement("link"));
link.type = "text/css";
link.rel = "stylesheet";
link.href = this.address;
// wait until the css file is loaded
this._loadPromise = new Promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject("Unable to load CSS");
}, CssModule.waitTimeout * 1000);
var linkEventCallback = function(event) {
clearTimeout(timeout);
link.removeEventListener("load", linkEventCallback);
link.removeEventListener("error", linkEventCallback);
if (event && event.type === "error") {
reject("Unable to load CSS");
} else {
resolve("");
}
};
link.addEventListener("load", linkEventCallback);
link.addEventListener("error", linkEventCallback);
document.head.appendChild(link);
});
return this._loadPromise;
};