-
Notifications
You must be signed in to change notification settings - Fork 4
/
streaming-element.js
52 lines (44 loc) · 1.47 KB
/
streaming-element.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
customElements.define('streaming-element', class StreamingElement extends HTMLElement {
constructor() {
super();
const iframeReady = new Promise(resolve => {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.onload = () => {
iframe.onload = null;
resolve(iframe);
};
iframe.src = '';
});
async function end() {
const iframe = await iframeReady;
iframe.contentDocument.write('</streaming-element-inner>');
iframe.contentDocument.close();
iframe.remove();
}
this.writable = new WritableStream({
start: async () => {
const iframe = await iframeReady;
iframe.contentDocument.write('<streaming-element-inner>');
this.appendChild(iframe.contentDocument.querySelector('streaming-element-inner'));
},
async write(chunk) {
const iframe = await iframeReady;
iframe.contentDocument.write(chunk);
},
close: end,
abort: end
});
}
});
document.querySelector('.streaming-element').addEventListener('click', async () => {
const content = document.querySelector('.content');
content.innerHTML = '';
const streamingElement = document.createElement('streaming-element');
content.appendChild(streamingElement);
const response = await fetch('comments.inc.txt');
response.body
.pipeThrough(new TextDecoder())
.pipeTo(streamingElement.writable);
});