Skip to content

Commit 4927388

Browse files
alpadevXhmikosR
andauthored
Register only one DOMContentLoaded event listener in onDOMContentLoaded (#34158)
* refactor: reuse one DOMContentLoaded event listener in onDOMContentLoaded function Instead of adding an event listener everytime the utility function is called, cache the callbacks and execute them all at once. * refactor: drop iife for onDOMContentLoaded Co-authored-by: XhmikosR <[email protected]>
1 parent 56b0004 commit 4927388

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

js/src/util/index.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,18 @@ const getjQuery = () => {
201201
return null
202202
}
203203

204+
const DOMContentLoadedCallbacks = []
205+
204206
const onDOMContentLoaded = callback => {
205207
if (document.readyState === 'loading') {
206-
document.addEventListener('DOMContentLoaded', callback)
208+
// add listener on the first call when the document is in loading state
209+
if (!DOMContentLoadedCallbacks.length) {
210+
document.addEventListener('DOMContentLoaded', () => {
211+
DOMContentLoadedCallbacks.forEach(callback => callback())
212+
})
213+
}
214+
215+
DOMContentLoadedCallbacks.push(callback)
207216
} else {
208217
callback()
209218
}

js/tests/unit/util/index.spec.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -582,15 +582,24 @@ describe('Util', () => {
582582
})
583583

584584
describe('onDOMContentLoaded', () => {
585-
it('should execute callback when DOMContentLoaded is fired', () => {
585+
it('should execute callbacks when DOMContentLoaded is fired and should not add more than one listener', () => {
586586
const spy = jasmine.createSpy()
587+
const spy2 = jasmine.createSpy()
588+
589+
spyOn(document, 'addEventListener').and.callThrough()
587590
spyOnProperty(document, 'readyState').and.returnValue('loading')
591+
588592
Util.onDOMContentLoaded(spy)
589-
window.document.dispatchEvent(new Event('DOMContentLoaded', {
593+
Util.onDOMContentLoaded(spy2)
594+
595+
document.dispatchEvent(new Event('DOMContentLoaded', {
590596
bubbles: true,
591597
cancelable: true
592598
}))
599+
593600
expect(spy).toHaveBeenCalled()
601+
expect(spy2).toHaveBeenCalled()
602+
expect(document.addEventListener).toHaveBeenCalledTimes(1)
594603
})
595604

596605
it('should execute callback if readyState is not "loading"', () => {

0 commit comments

Comments
 (0)