forked from thomaswilburn/async-await-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.js
71 lines (56 loc) · 2.06 KB
/
loader.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
/*
let's define our own module system, why not, that's always ended well.
- install() is the equivalent of require, returns a promise
- install.batch() will load multiple files in parallel
- install.patch() == AMD's define(), but does not accept dependencies (use async functions to do that)
- install.stylesheet() adds a link tag for async styles
*/
(function() {
var prefix = document.currentScript.src.replace(/\/[^\/]*?.js$/, "/");
var joinPath = function(base, ...rest) {
var parts = base.split("/");
while (parts[parts.length - 1] == "") parts.pop();
rest.forEach(function(path) {
var segments = path.split("/");
segments.forEach(function(p) {
if (!p || p == ".") return;
if (p == "..") return parts.pop();
parts.push(p);
});
});
return parts.join("/");
};
var modules = {};
var requests = {};
window.install = function(path) {
path = path.replace(/\.js$/, "");
if (modules[path]) return modules[path];
if (!requests[path]) requests[path] = new Promise(function(ok, fail) {
var script = document.createElement("script");
var url = joinPath(prefix, path) + ".js";
script.src = url;
script.setAttribute("data-module", path);
document.body.appendChild(script);
script.onload = () => ok();
script.onerror = fail;
});
return requests[path].then(() => modules[path]);
};
window.install.patch = function(module) {
var script = document.currentScript;
var path = script.getAttribute("data-module");
if (typeof module == "function") module = module();
modules[path] = Promise.resolve(module);
};
window.install.stylesheet = function(url) {
var link = document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("href", url);
document.head.appendChild(link);
};
window.install.batch = function(...urls) {
return Promise.all(urls.map(u => install(u)));
};
var root = document.currentScript ? document.currentScript.getAttribute("data-main") : "";
if (root) install(root);
})();