|
1 | 1 | import { mount } from 'svelte'; |
2 | 2 | import type { SvelteComponent } from 'svelte'; |
3 | 3 |
|
| 4 | +declare global { |
| 5 | + interface Window { |
| 6 | + $?: unknown; |
| 7 | + } |
| 8 | +} |
| 9 | + |
4 | 10 | export default async function mountEmbeds( |
5 | 11 | Component: typeof SvelteComponent, |
6 | 12 | targetSelector: string |
7 | 13 | ): Promise<void> { |
8 | | - const _mountEmbeds = () => { |
9 | | - console.log( |
10 | | - `Mounting components for selector: ${targetSelector}`, |
11 | | - document.querySelectorAll(targetSelector) |
12 | | - ); |
13 | | - document.querySelectorAll(targetSelector).forEach((target) => { |
14 | | - console.log(`Mounting individual component on target:`, target); |
15 | | - mount(Component, { target }); |
16 | | - }); |
17 | | - }; |
| 14 | + const _mountEmbeds = () => |
| 15 | + (() => { |
| 16 | + console.log( |
| 17 | + `Mounting components for selector: ${targetSelector}`, |
| 18 | + document.querySelectorAll(targetSelector) |
| 19 | + ); |
| 20 | + document.querySelectorAll(targetSelector).forEach((target) => { |
| 21 | + console.log(`Mounting individual component on target:`, target); |
| 22 | + mount(Component, { target }); |
| 23 | + }); |
| 24 | + })(); |
| 25 | + |
| 26 | + // Mount the components on initial load |
| 27 | + console.log('Mounting Datawrapper Switcher on initial load'); |
| 28 | + _mountEmbeds(); |
18 | 29 |
|
19 | 30 | // Listen for PJAX navigation events to remount the component if needed |
20 | 31 | if (window.$) { |
21 | 32 | $(document).on('pjax:end', () => { |
22 | | - console.log('PJAX navigation detected (jQuery), remounting Datawrapper Switcher'); |
23 | | - _mountEmbeds(); |
| 33 | + // Delay to ensure new DOM is ready before attempting to mount |
| 34 | + setTimeout(() => _mountEmbeds(), 100); |
24 | 35 | }); |
25 | 36 | } |
26 | | - |
27 | | - // Mount the components on initial load |
28 | | - console.log('Mounting Datawrapper Switcher on initial load'); |
29 | | - _mountEmbeds(); |
30 | 37 | } |
0 commit comments