forked from seajs/seajs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin-text.js
136 lines (107 loc) · 2.67 KB
/
plugin-text.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/**
* The plugin to load text resources such as template, json
*/
(function(seajs, global) {
var plugins = {}
var uriCache = {}
function addPlugin(o) {
plugins[o.name] = o
}
// normal text
addPlugin({
name: "text",
ext: [".tpl", ".html"],
exec: function(content) {
globalEval('define("' + jsEscape(content) + '")')
}
})
// json
addPlugin({
name: "json",
ext: [".json"],
exec: function(content) {
globalEval("define(" + content + ")")
}
})
seajs.on("resolve", function(data) {
var id = data.id
var pluginName
var m
// text!path/to/some.xx
if ((m = id.match(/^(\w+)!(.+)$/)) && isPlugin(m[1])) {
pluginName = m[1]
id = m[2]
}
var uri = data.id2Uri(id, data.refUri)
var t = uri.replace(/\.(?:js|css)(\?|$)/, "$1")
// http://path/to/a.tpl
// http://path/to/c.json?v2
if (!pluginName && (m = t.match(/[^?]+(\.\w+)(?:\?|$)/))) {
pluginName = getPluginName(m[1])
}
if (pluginName) {
uri = uri.replace(/\.js$/, "")
uriCache[uri] = pluginName
}
data.uri = uri
})
seajs.on("request", function(data) {
var uri = data.uri
var name = uriCache[uri]
if (name) {
xhr(uri, function(content) {
plugins[name].exec(content)
data.callback()
})
data.requested = true
}
})
// Helpers
function isPlugin(name) {
return name && plugins.hasOwnProperty(name)
}
function getPluginName(ext) {
for (var k in plugins) {
if (isPlugin(k)) {
var exts = "," + plugins[k].ext.join(",") + ","
if (exts.indexOf("," + ext + ",") > -1) {
return k
}
}
}
}
function xhr(url, callback) {
var r = global.ActiveXObject ?
new global.ActiveXObject("Microsoft.XMLHTTP") :
new global.XMLHttpRequest()
r.open("GET", url, true)
r.onreadystatechange = function() {
if (r.readyState === 4) {
if (r.status === 200) {
callback(r.responseText)
}
else {
throw new Error("Could not load: " + url + ", status = " + r.status)
}
}
}
return r.send(null)
}
function globalEval(data) {
if (data && /\S/.test(data)) {
(global.execScript || function(data) {
global["eval"].call(global, data)
})(data)
}
}
function jsEscape(content) {
return content.replace(/(["\\])/g, "\\$1")
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r")
.replace(/[\u2028]/g, "\\u2028")
.replace(/[\u2029]/g, "\\u2029")
}
})(seajs, this);