Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ecce92e

Browse files
committed
refactor: be more explicit about task queueing
1 parent 6007ed4 commit ecce92e

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/index.ts

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,9 @@ const observer = new IntersectionObserver(entries => {
2121
})
2222

2323

24-
function fire(name: string, target: Element): Promise<void> {
25-
return new Promise(resolve => {
26-
setTimeout(function () {
27-
target.dispatchEvent(new Event(name))
28-
resolve()
29-
}, 0)
30-
})
24+
// Functional stand in for the W3 spec "queue a task" paradigm
25+
function task(): Promise<void> {
26+
return new Promise(resolve => setTimeout(resolve, 0))
3127
}
3228

3329
async function handleData(el: IncludeFragmentElement) {
@@ -152,8 +148,11 @@ export default class IncludeFragmentElement extends HTMLElement {
152148
load(): Promise<string> {
153149
observer.unobserve(this)
154150
return Promise.resolve()
155-
.then(() => fire('loadstart', this))
156-
.then(() => this.fetch(this.request()))
151+
.then(task)
152+
.then(() => {
153+
this.dispatchEvent(new Event('loadstart'))
154+
return this.fetch(this.request())
155+
})
157156
.then(response => {
158157
if (response.status !== 200) {
159158
throw new Error(`Failed to load resource: the server responded with a status of ${response.status}`)
@@ -165,10 +164,16 @@ export default class IncludeFragmentElement extends HTMLElement {
165164
return response.text()
166165
})
167166
.then(data => {
168-
fire('load', this).then(() => fire('loadend', this))
167+
task().then(() => {
168+
this.dispatchEvent(new Event('load'))
169+
this.dispatchEvent(new Event('loadend'))
170+
})
169171
return data
170172
}, error => {
171-
fire('error', this).then(() => fire('loadend', this))
173+
task().then(() => {
174+
this.dispatchEvent(new Event('error'))
175+
this.dispatchEvent(new Event('loadend'))
176+
})
172177
throw error
173178
})
174179
}

0 commit comments

Comments
 (0)