From ee0dc3c1101e58e6655583534bc58abdd750519b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Oddsson?= Date: Wed, 30 Mar 2022 14:32:22 +0100 Subject: [PATCH 1/2] Check if there's a network request already in flight --- src/index.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/index.ts b/src/index.ts index 3561f24..86c16ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -50,6 +50,8 @@ export default class IncludeFragmentElement extends HTMLElement { return this.#getData() } + #busy = false + attributeChangedCallback(attribute: string, oldVal: string | null): void { if (attribute === 'src') { // Source changed after attached so replace element. @@ -132,6 +134,9 @@ export default class IncludeFragmentElement extends HTMLElement { ) #handleData(): Promise { + if (this.#busy) return Promise.resolve() + this.#busy = true + this.#observer.unobserve(this) return this.#getData().then( (html: string) => { From 155a8cb84cc1ddc57acdf014d76bbcc90a9dd41a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Oddsson?= Date: Thu, 31 Mar 2022 15:50:34 +0100 Subject: [PATCH 2/2] Add test to make sure `include-fragment-replaced` is called once --- test/test.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/test.js b/test/test.js index 81bc9a4..f54b45a 100644 --- a/test/test.js +++ b/test/test.js @@ -587,4 +587,24 @@ suite('include-fragment-element', function () { assert.equal(document.querySelector('#replaced').textContent, 'hello') }) }) + + test('include-fragment-replaced is only called once', function () { + const div = document.createElement('div') + div.hidden = true + document.body.append(div) + + div.innerHTML = `loading` + div.firstChild.addEventListener('include-fragment-replaced', () => (loadCount += 1)) + + let loadCount = 0 + setTimeout(() => { + div.hidden = false + }, 0) + + return when(div.firstChild, 'include-fragment-replaced').then(() => { + assert.equal(loadCount, 1, 'Load occured too many times') + assert.equal(document.querySelector('include-fragment'), null) + assert.equal(document.querySelector('#replaced').textContent, 'hello') + }) + }) })