Skip to content

Commit

Permalink
DomReady: Fix race condition (#8578)
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad authored and omarreiss committed Aug 6, 2018
1 parent 81bc778 commit fb03f0b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
6 changes: 5 additions & 1 deletion packages/dom-ready/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
};

Expand Down
21 changes: 17 additions & 4 deletions packages/dom-ready/src/test/index.test.js
Original file line number Diff line number Diff line change
@@ -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();
} );
Expand All @@ -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,
} );
Expand Down

0 comments on commit fb03f0b

Please sign in to comment.