diff --git a/src/preview.ts b/src/preview.ts index 58355e4b..5b971e55 100644 --- a/src/preview.ts +++ b/src/preview.ts @@ -144,7 +144,13 @@ export class PreviewPlugin implements Plugin { } }); - document.body.prepend(widget); + const insert = (): void => document.body?.prepend(widget); + + if (document.readyState === 'complete') { + insert(); + } else { + window.addEventListener('DOMContentLoaded', insert); + } } private updateUrl(): void { diff --git a/test/preview.test.ts b/test/preview.test.ts index 8369eeb8..e1452f38 100644 --- a/test/preview.test.ts +++ b/test/preview.test.ts @@ -253,6 +253,30 @@ describe('A Preview plugin', () => { expect(src.searchParams.get('variant')).toBe(metadata.variantName); }); + it('should insert the widget when the document is ready', () => { + Object.defineProperty(document, 'readyState', { + writable: true, + value: 'loading', + }); + + const plugin = new PreviewPlugin(configuration); + + configuration.tokenStore.setToken(token); + + plugin.enable(); + + expect(document.body.querySelector('iframe')).toBe(null); + + Object.defineProperty(document, 'readyState', { + writable: true, + value: 'complete', + }); + + window.dispatchEvent(new Event('DOMContentLoaded')); + + expect(document.body.querySelector('iframe')).not.toBe(null); + }); + it('should ignore messages from unknown origins', () => { const plugin = new PreviewPlugin(configuration);