Fix link-once and script-once not triggering when another one disappears

This commit is contained in:
2026-03-26 16:05:05 +01:00
parent 182cdbe590
commit d26a154870
3 changed files with 48 additions and 19 deletions

View File

@@ -6,14 +6,36 @@ import { inheritHtmlElement, registerComponent } from "#core:utils/web-component
**/
@registerComponent("link-once")
export class LinkOnce extends inheritHtmlElement("link") {
connectedCallback() {
super.connectedCallback(false);
refresh() {
this.clearNode();
// We get href from node.attributes instead of node.href to avoid getting the domain part
const href = this.node.attributes.getNamedItem("href").nodeValue;
if (document.querySelectorAll(`link[href='${href}']`).length === 0) {
this.appendChild(this.node);
}
}
clearNode() {
while (this.firstChild) {
this.removeChild(this.lastChild);
}
}
connectedCallback() {
super.connectedCallback(false);
this.refresh();
}
disconnectedCallback() {
this.clearNode();
// This re-triggers link-once elements that still exists and suppressed
// themeselves once it gets removed from the page
for (const link of document.getElementsByTagName("link-once")) {
(link as LinkOnce).refresh();
}
}
}
/**
@@ -22,12 +44,34 @@ export class LinkOnce extends inheritHtmlElement("link") {
**/
@registerComponent("script-once")
export class ScriptOnce extends inheritHtmlElement("script") {
connectedCallback() {
super.connectedCallback(false);
refresh() {
this.clearNode();
// We get src from node.attributes instead of node.src to avoid getting the domain part
const src = this.node.attributes.getNamedItem("src").nodeValue;
if (document.querySelectorAll(`script[src='${src}']`).length === 0) {
this.appendChild(this.node);
}
}
clearNode() {
while (this.firstChild) {
this.removeChild(this.lastChild);
}
}
connectedCallback() {
super.connectedCallback(false);
this.refresh();
}
disconnectedCallback() {
this.clearNode();
// This re-triggers script-once elements that still exists and suppressed
// themeselves once it gets removed from the page
for (const link of document.getElementsByTagName("script-once")) {
(link as LinkOnce).refresh();
}
}
}

View File

@@ -1,14 +1,7 @@
{% extends "core/base.jinja" %}
{%- block additional_js -%}
<script type="module" src="{{ static("bundled/core/components/ajax-select-index.ts") }}"></script>
{%- endblock -%}
{%- block additional_css -%}
<link rel="stylesheet" href="{{ static('user/user_preferences.scss') }}">
{# importing ajax-select-index is necessary for it to be applied after HTMX reload #}
<link rel="stylesheet" href="{{ static("bundled/core/components/ajax-select-index.css") }}">
<link rel="stylesheet" href="{{ static("core/components/ajax-select.scss") }}">
{%- endblock -%}
{% block title %}