Skip to content

Commit

Permalink
refactor: reuse one DOMContentLoaded event listener in onDOMContentLo…
Browse files Browse the repository at this point in the history
…aded function

Instead of adding an event listener everytime the utility function is called, cache the callbacks and execute them all at once.
  • Loading branch information
alpadev committed Jun 2, 2021
1 parent 7d9adb7 commit 7278a2b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
23 changes: 17 additions & 6 deletions js/src/util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,24 @@ const getjQuery = () => {
return null
}

const onDOMContentLoaded = callback => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callback)
} else {
callback()
const onDOMContentLoaded = (() => {
const callbacks = []

return callback => {
if (document.readyState === 'loading') {
// add listener on the first call when the document is in loading state
if (!callbacks.length) {
document.addEventListener('DOMContentLoaded', () => {
callbacks.forEach(callback => callback())
})
}

callbacks.push(callback)
} else {
callback()
}
}
}
})()

const isRTL = () => document.documentElement.dir === 'rtl'

Expand Down
11 changes: 10 additions & 1 deletion js/tests/unit/util/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -608,15 +608,24 @@ describe('Util', () => {
})

describe('onDOMContentLoaded', () => {
it('should execute callback when DOMContentLoaded is fired', () => {
it('should execute callbacks when DOMContentLoaded is fired and should not add more than one listener', () => {
const spy = jasmine.createSpy()
const spy2 = jasmine.createSpy()

spyOn(document, 'addEventListener').and.callThrough()
spyOnProperty(document, 'readyState').and.returnValue('loading')

Util.onDOMContentLoaded(spy)
Util.onDOMContentLoaded(spy2)

window.document.dispatchEvent(new Event('DOMContentLoaded', {
bubbles: true,
cancelable: true
}))

expect(spy).toHaveBeenCalled()
expect(spy2).toHaveBeenCalled()
expect(document.addEventListener).toHaveBeenCalledTimes(1)
})

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

0 comments on commit 7278a2b

Please sign in to comment.