我遇到使用AMP.attachShadowDocAsStream流式传输到shadowDom的问题。
我的设置几乎与AMP文档中的示例相同:
const shadowDoc = AMP.attachShadowDocAsStream(ampContainer, url, {});
shadowDoc.writer.onBodyChunk(function(){
console.log('chunk added');
});
fetch(url, {credentials: 'include'}).then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
function readChunk() {
console.log('chuck recieved');
return reader.read().then(chunk => {
let text = decoder.decode(
chunk.value || new Uint8Array(),
{stream: !chunk.done});
if (text) {
shadowDoc.writer.write(text);
}
if (chunk.done) {
shadowDoc.writer.close();
} else {
return readChunk();
}
});
}
return readChunk();
});
请求的网址只返回:
<!doctype html>
<html lang="en" data-docformat="amp" ⚡>
<head></head>
<body id="body">
<% for (var i = 0; i < 1000; i++) { %>
<div>
<h1><strong><%= i %></strong> - This is a load of self contained data</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</div>
<% } %>
</body>
</html>
虽然我可以从console.log中看到shadowDoc.writer正在向节点添加块(也是页面大小增加,如滚动条所示)。 dom内容在调用shadowDoc.writer.end()之前不会呈现,因此首先否定了流式传输html中的重点。
当dom被添加时,是否可以强制渲染每个块?