Skip to content

Commit 2de67e7

Browse files
progressive hydration for SSG example
1 parent 30eb7d7 commit 2de67e7

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

ssg.js

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,77 @@ await fse.copy('./www/components', `${distRoot}/www/components`)
1313
await fse.copy('./www/pages', `${distRoot}/www/pages`)
1414

1515
for (const entry of entries.filter(entry => entry.endsWith('.js'))) {
16-
const { html } = await renderToString(new URL(`${pagesRoot}/${entry}`, import.meta.url), false);
16+
const { html, assets } = await renderToString(new URL(`${pagesRoot}/${entry}`, import.meta.url), false);
17+
18+
const lazyJs = [];
19+
const eagerJs = [];
20+
21+
for(const asset in assets) {
22+
const a = assets[asset];
23+
24+
a.tagName = asset;
25+
26+
if(a.moduleURL.href.endsWith('.js')) {
27+
if(a.hydrate === 'lazy') {
28+
lazyJs.push(a)
29+
} else {
30+
eagerJs.push(a)
31+
}
32+
}
33+
}
1734

1835
// bundle / copy dependency files
1936
await fs.writeFile(new URL(`${distRoot}/${entry.replace('.js', '.html')}`, import.meta.url), `
2037
<!DOCTYPE html>
2138
<html>
2239
<head>
2340
<title>WCC</title>
41+
42+
${
43+
eagerJs.map(script => {
44+
return `<script type="module" src="${script.moduleURL.pathname.replace(process.cwd(), '')}"></script>`
45+
}).join('\n')
46+
}
47+
48+
${
49+
lazyJs.map(script => {
50+
return `
51+
<script type="module">
52+
let initialized = false;
53+
54+
window.addEventListener('load', () => {
55+
let options = {
56+
root: null,
57+
rootMargin: '20px',
58+
threshold: 1.0
59+
}
60+
61+
let callback = (entries, observer) => {
62+
entries.forEach(entry => {
63+
console.debug({ entry })
64+
if(!initialized && entry.isIntersecting) {
65+
alert('Intersected ${script.tagName}, time to hydrate!!!');
66+
initialized = true;
67+
import('${script.moduleURL.pathname.replace(process.cwd(), '')}')
68+
}
69+
});
70+
}
71+
72+
let observer = new IntersectionObserver(callback, options);
73+
let target = document.querySelector('${script.tagName}');
74+
75+
observer.observe(target);
76+
})
77+
</script>
78+
`
79+
}).join('\n')
80+
}
2481
</head>
2582
<body>
2683
${html}
2784
2885
<script type="module">
29-
import PageEntry from '${pagesRoot}/${entry}';
86+
// import PageEntry from '${pagesRoot}/${entry}';
3087
</script>
3188
</body>
3289
</html>

0 commit comments

Comments
 (0)