return null
}
+const DOMContentLoadedCallbacks = []
+
const onDOMContentLoaded = callback => {
if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', callback)
+ // add listener on the first call when the document is in loading state
+ if (!DOMContentLoadedCallbacks.length) {
+ document.addEventListener('DOMContentLoaded', () => {
+ DOMContentLoadedCallbacks.forEach(callback => callback())
+ })
+ }
+
+ DOMContentLoadedCallbacks.push(callback)
} else {
callback()
}
})
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)
- window.document.dispatchEvent(new Event('DOMContentLoaded', {
+ Util.onDOMContentLoaded(spy2)
+
+ 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"', () => {