diff --git a/packages/dom-ready/src/index.js b/packages/dom-ready/src/index.js index e04cc58252931f..f19b862e0e28c3 100644 --- a/packages/dom-ready/src/index.js +++ b/packages/dom-ready/src/index.js @@ -6,10 +6,14 @@ * @return {void} */ const domReady = function( callback ) { - if ( document.readyState === 'complete' ) { + if ( + document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly. + document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly. + ) { return callback(); } + // DOMContentLoaded has not fired yet, delay callback until then. document.addEventListener( 'DOMContentLoaded', callback ); }; diff --git a/packages/dom-ready/src/test/index.test.js b/packages/dom-ready/src/test/index.test.js index 7730c8151d80e2..63a0d6f4b3ae4a 100644 --- a/packages/dom-ready/src/test/index.test.js +++ b/packages/dom-ready/src/test/index.test.js @@ -1,10 +1,26 @@ import domReady from '../'; describe( 'domReady', () => { + beforeAll( () => { + Object.defineProperty( document, 'readyState', { + value: 'loading', + writable: true, + } ); + } ); + describe( 'when document readystate is complete', () => { it( 'should call the callback.', () => { const callback = jest.fn( () => {} ); + document.readyState = 'complete'; + domReady( callback ); + expect( callback ).toHaveBeenCalled(); + } ); + } ); + describe( 'when document readystate is interactive', () => { + it( 'should call the callback.', () => { + const callback = jest.fn( () => {} ); + document.readyState = 'interactive'; domReady( callback ); expect( callback ).toHaveBeenCalled(); } ); @@ -13,10 +29,7 @@ describe( 'domReady', () => { describe( 'when document readystate is still loading', () => { it( 'should add the callback as an event listener to the DOMContentLoaded event.', () => { const addEventListener = jest.fn( () => {} ); - - Object.defineProperty( document, 'readyState', { - value: 'loading', - } ); + document.readyState = 'loading'; Object.defineProperty( document, 'addEventListener', { value: addEventListener, } );