Skip to content

Commit

Permalink
Merge pull request #79 from github/check-if-network-request-is-alread…
Browse files Browse the repository at this point in the history
…y-in-flight

Check if there's a network request already in flight
  • Loading branch information
koddsson authored Mar 31, 2022
2 parents b5007c8 + 155a8cb commit c405e3a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -132,6 +134,9 @@ export default class IncludeFragmentElement extends HTMLElement {
)

#handleData(): Promise<void> {
if (this.#busy) return Promise.resolve()
this.#busy = true

this.#observer.unobserve(this)
return this.#getData().then(
(html: string) => {
Expand Down
20 changes: 20 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `<include-fragment src="/hello">loading</include-fragment>`
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')
})
})
})

0 comments on commit c405e3a

Please sign in to comment.