This repository has been archived by the owner on Dec 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
async-fragments-tag.js
71 lines (54 loc) · 2.2 KB
/
async-fragments-tag.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
var clientReorder = require('./client-reorder');
module.exports = function(input, out) {
var global = out.global;
out.flush();
var asyncOut = out.beginAsync({ last: true, timeout: -1, name: 'async-fragments' });
out.onLast(function(next) {
var asyncFragmentsContext = global.__asyncFragments;
if (!asyncFragmentsContext || !asyncFragmentsContext.fragments.length) {
asyncOut.end();
next();
return;
}
var remaining = asyncFragmentsContext.fragments.length;
var done = false;
function handleAsyncFragment(fragmentInfo) {
fragmentInfo.asyncValue.done(function(err, html) {
if (done) {
return;
}
if (err) {
done = true;
return asyncOut.error(err);
}
if (!global._afRuntime) {
asyncOut.write(clientReorder.getCode());
global._afRuntime = true;
}
asyncOut.write('<div id="af' + fragmentInfo.id + '" style="display:none">' +
html +
'</div>' +
'<script type="text/javascript">$af(' +
(typeof fragmentInfo.id === 'number' ? fragmentInfo.id : '"' + fragmentInfo.id + '"') +
(fragmentInfo.after ? (',"' + fragmentInfo.after + '"') : '' ) +
')</script>');
fragmentInfo.out.writer = asyncOut.writer;
out.emit('asyncFragmentFinish', fragmentInfo);
out.flush();
if (--remaining === 0) {
done = true;
asyncOut.end();
next();
}
});
}
asyncFragmentsContext.fragments.forEach(handleAsyncFragment);
out.on('asyncFragmentClientReorder', function(fragmentInfo) {
remaining++;
handleAsyncFragment(fragmentInfo);
});
// Now that we have a listener attached, we want to receive any additional
// out-of-sync fragments via an event
delete asyncFragmentsContext.fragments;
});
};