Skip to content

Commit cb8ec47

Browse files
committed
Defer initialization after PJAX navigation
1 parent 8fb8f1c commit cb8ec47

File tree

3 files changed

+32
-16
lines changed

3 files changed

+32
-16
lines changed

package-lock.json

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

sophora-components/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"@eslint/js": "^9.39.2",
1818
"@sveltejs/vite-plugin-svelte": "^6.2.4",
1919
"@swr-data-lab/components": "^2.43.0",
20+
"@types/jquery": "^4.0.0",
2021
"@types/node": "^22",
2122
"eslint": "^9.39.2",
2223
"eslint-config-prettier": "^10.1.8",
Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,37 @@
11
import { mount } from 'svelte';
22
import type { SvelteComponent } from 'svelte';
33

4+
declare global {
5+
interface Window {
6+
$?: unknown;
7+
}
8+
}
9+
410
export default async function mountEmbeds(
511
Component: typeof SvelteComponent,
612
targetSelector: string
713
): 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();
1829

1930
// Listen for PJAX navigation events to remount the component if needed
2031
if (window.$) {
2132
$(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);
2435
});
2536
}
26-
27-
// Mount the components on initial load
28-
console.log('Mounting Datawrapper Switcher on initial load');
29-
_mountEmbeds();
3037
}

0 commit comments

Comments
 (0)