mirror of
https://github.com/wagtail/wagtail.git
synced 2024-11-29 01:22:07 +01:00
Create shared util domReady
This commit is contained in:
parent
0ba6cb726c
commit
4195f80d29
36
client/src/utils/domReady.test.js
Normal file
36
client/src/utils/domReady.test.js
Normal file
@ -0,0 +1,36 @@
|
||||
import { domReady } from './domReady';
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
describe('domReady', () => {
|
||||
it('should resolve as true if the DOM is not in loading state', () => {
|
||||
expect(document.readyState).toEqual('complete');
|
||||
|
||||
return domReady().then(() => {
|
||||
expect(document.readyState).toEqual('complete');
|
||||
});
|
||||
});
|
||||
|
||||
it('should resolve as true if the DOM loading but then completes loading', () => {
|
||||
let trackingValue = null;
|
||||
|
||||
Object.defineProperty(document, 'readyState', {
|
||||
value: 'loading',
|
||||
});
|
||||
|
||||
expect(document.readyState).toEqual('loading');
|
||||
|
||||
setTimeout(() => {
|
||||
trackingValue = true;
|
||||
document.dispatchEvent(new CustomEvent('DOMContentLoaded'));
|
||||
}, 5);
|
||||
|
||||
const promise = domReady();
|
||||
|
||||
jest.runAllTimers();
|
||||
|
||||
return promise.then(() => {
|
||||
expect(trackingValue).toEqual(true);
|
||||
});
|
||||
});
|
||||
});
|
16
client/src/utils/domReady.ts
Normal file
16
client/src/utils/domReady.ts
Normal file
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Returns a promise that resolves once the DOM is ready for interaction.
|
||||
*/
|
||||
const domReady = async () =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => resolve(), {
|
||||
once: true,
|
||||
passive: true,
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
|
||||
export { domReady };
|
Loading…
Reference in New Issue
Block a user