Here’s a neat trick.
Fred K. Schott gives an impressive presentation of Astro, a framework-agnostic architecture for building web sites and web apps.
We add a script to the end of your page. It’s inline. It essentially runs almost immediately, and that is what is going to create that Intersection Observer. It’s going to do a dynamic import of the things that you need, and it’s going to call React render on that component.
During the presentation, Fred demonstrates dynamically loading JS using "Islands Architecture", a strategy where small HTML placeholders are progressively upgraded with dynamic or interactive content as-needed.
The demonstration involves
waiting on the viewport visibility of a div placeholder before loading some JS.
The entire setup contributes less than 200 bytes to the page when gzipped.
<div data-astro-id="3459833264469372"></div>
<script type="module">
/* scaffolding put before the code */
((o=new IntersectionObserver((([{isIntersecting,target}])=>{isIntersecting&&(o.disconnect(),
/* code run when the section is visible */
Promise.all([
import('https://cdn.skypack.dev/react'),
import('https://cdn.skypack.dev/react-dom'),
]).then( ([
{ default: React },
{ default: ReactDOM },
]) => ReactDOM.render(
React.createElement('strong', {},
'This was rendered with React!',
),
target,
) )
/* scaffolding put after the code */
)})))=>{o.observe(document.querySelector('[data-astro-id="3459833264469372"]'))})()
</script>
Neat trick, right?
It can be used once, or multiple times in different places. JS can be loaded by element visibility, a media query, a container query, any event, any asset, any idle period, or any mix of these, and any other condition that’s helpful.
Below is a live demonstration.
👇
👆
Above is a live demonstration.
That’s all.
It just seems like a neat trick.