-
Notifications
You must be signed in to change notification settings - Fork 631
/
web-loaders.js
95 lines (82 loc) · 2.43 KB
/
web-loaders.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
'use strict';
const Loader = require('./loader');
const {PrecompiledLoader} = require('./precompiled-loader.js');
class WebLoader extends Loader {
constructor(baseURL, opts) {
super();
this.baseURL = baseURL || '.';
opts = opts || {};
// By default, the cache is turned off because there's no way
// to "watch" templates over HTTP, so they are re-downloaded
// and compiled each time. (Remember, PRECOMPILE YOUR
// TEMPLATES in production!)
this.useCache = !!opts.useCache;
// We default `async` to false so that the simple synchronous
// API can be used when you aren't doing anything async in
// your templates (which is most of the time). This performs a
// sync ajax request, but that's ok because it should *only*
// happen in development. PRECOMPILE YOUR TEMPLATES.
this.async = !!opts.async;
}
resolve(from, to) {
throw new Error('relative templates not support in the browser yet');
}
getSource(name, cb) {
var useCache = this.useCache;
var result;
this.fetch(this.baseURL + '/' + name, (err, src) => {
if (err) {
if (cb) {
cb(err.content);
} else if (err.status === 404) {
result = null;
} else {
throw err.content;
}
} else {
result = {
src: src,
path: name,
noCache: !useCache
};
this.emit('load', name, result);
if (cb) {
cb(null, result);
}
}
});
// if this WebLoader isn't running asynchronously, the
// fetch above would actually run sync and we'll have a
// result here
return result;
}
fetch(url, cb) {
// Only in the browser please
if (typeof window === 'undefined') {
throw new Error('WebLoader can only by used in a browser');
}
const ajax = new XMLHttpRequest();
let loading = true;
ajax.onreadystatechange = () => {
if (ajax.readyState === 4 && loading) {
loading = false;
if (ajax.status === 0 || ajax.status === 200) {
cb(null, ajax.responseText);
} else {
cb({
status: ajax.status,
content: ajax.responseText
});
}
}
};
url += (url.indexOf('?') === -1 ? '?' : '&') + 's=' +
(new Date().getTime());
ajax.open('GET', url, this.async);
ajax.send();
}
}
module.exports = {
WebLoader: WebLoader,
PrecompiledLoader: PrecompiledLoader
};