Skip to content

Check if there's a network request already in flight #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')
})
})
})