fix double script execution issue when using template parsing

This commit is contained in:
Carson Gross 2024-03-13 18:11:58 -06:00
parent 83e939a370
commit ef791c51eb
2 changed files with 27 additions and 11 deletions

View File

@ -309,10 +309,24 @@ return (function () {
content = content.replace(HEAD_TAG_REGEX, '');
}
if (htmx.config.useTemplateFragments && partialResponse) {
var documentFragment = parseHTML("<body><template>" + content + "</template></body>", 0);
var fragment = parseHTML("<body><template>" + content + "</template></body>", 0);
// @ts-ignore type mismatch between DocumentFragment and Element.
// TODO: Are these close enough for htmx to use interchangeably?
return documentFragment.querySelector('template').content;
if (htmx.config.allowScriptTags) {
// if there is a nonce set up, set it on the new script tags
forEach(fragment.querySelectorAll("script"), function (script) {
if (htmx.config.inlineScriptNonce) {
script.nonce = htmx.config.inlineScriptNonce;
}
getInternalData(script).executed = true; // mark as executed due to template insertion semantics
})
} else {
forEach(fragment.querySelectorAll("script"), function (script) {
// remove all script tags if scripts are disabled
removeElement(script);
})
}
return fragment.querySelector('template').content;
}
switch (startTag) {
case "thead":
@ -1892,7 +1906,8 @@ return (function () {
}
function evalScript(script) {
if (htmx.config.allowScriptTags && (script.type === "text/javascript" || script.type === "module" || script.type === "") ) {
if (!getInternalData(script).executed && htmx.config.allowScriptTags &&
(script.type === "text/javascript" || script.type === "module" || script.type === "") ) {
var newScript = getDocument().createElement("script");
forEach(script.attributes, function (attr) {
newScript.setAttribute(attr.name, attr.value);
@ -1918,12 +1933,14 @@ return (function () {
}
function processScripts(elt) {
if (matches(elt, "script")) {
evalScript(elt);
if (!htmx.config.useTemplateFragments) {
if (matches(elt, "script")) {
evalScript(elt);
}
forEach(findAll(elt, "script"), function (script) {
evalScript(script);
});
}
forEach(findAll(elt, "script"), function (script) {
evalScript(script);
});
}
function shouldProcessHxOn(elt) {

View File

@ -257,11 +257,11 @@ describe("Core htmx Regression Tests", function(){
div.click();
this.server.respond()
htmx.config.useTemplateFragments = oldUseTemplateFragmentsValue
setTimeout(function(){
window.i.should.equal(1);
delete window.i;
htmx.config.useTemplateFragments = oldUseTemplateFragmentsValue
done();
}, 50)
})
@ -278,11 +278,10 @@ describe("Core htmx Regression Tests", function(){
div.click();
this.server.respond()
htmx.config.useTemplateFragments = oldUseTemplateFragmentsValue
setTimeout(function(){
window.i.should.equal(1);
delete window.i;
htmx.config.useTemplateFragments = oldUseTemplateFragmentsValue
done();
}, 50)
})