原始地址:https://github.com/alarbada/htmx-stream
window.htmx.defineExtension("stream", {
onEvent: (name, evt) => {
if (name === "htmx:beforeRequest") {
let element = evt.detail.elt;
if (evt.detail.requestConfig.target) {
element.__target = evt.detail.requestConfig.target;
element = evt.detail.requestConfig.target;
}
const xhr = evt.detail.xhr;
let lastLength = 0;
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === 2 || xhr.readyState === 3) {
const newText = xhr.responseText.substring(lastLength);
element.__streamedChars = lastLength;
lastLength = xhr.responseText.length;
element.innerHTML = newText;
}
});
}
return true;
},
transformResponse: (text, _xhr, elt) => {
let lastLength = elt.__streamedChars;
const target = elt.__target;
if (target) {
lastLength = target.__streamedChars;
}
if (lastLength) {
const newText = text.substring(lastLength);
return newText;
}
return text;
}
});
标签:target,stream,htmx,detail,xhr,go,evt,lastLength
From: https://www.cnblogs.com/soarowl/p/18470520