Lazy loading
Every iframe embed sets loading="lazy", so the browser only loads it
when it is close to the viewport. The iframe is still in the page from
the first render, so it holds its space while you scroll and nothing
jumps as embeds arrive.
Load one straight away
Pass loading="eager" to any iframe embed. Do this for an embed at
the top of a page, where waiting for the browser to decide only delays
it.
1<YouTube youtube_id="dQw4w9WgXcQ" loading="eager" />Embeds without a loading prop
Bluesky, Threads, Tweet, Toot and Zencastr load in their own way, through the
platform’s script or a frame that sizes itself, and do not take a loading prop.
Lazy load your own markup
The package also exports in_view, the attachment to reach for when
you want the same behaviour for something that is not an iframe. It
calls on_enter when the element reaches the viewport.
1<script>
2 import { in_view } from 'sveltekit-embed';
3
4 let visible = $state(false);
5</script>
6
7<div {@attach in_view({ on_enter: () => (visible = true) })}>
8 {#if visible}
9 <!-- your content -->
10 {/if}
11</div>This box uses it. It was not in view yet.
Options
1interface InViewOptions {
2 /** Called when the element enters the viewport. */
3 on_enter: (entry: IntersectionObserverEntry) => void;
4 /** Called when the element leaves the viewport. */
5 on_leave?: (entry: IntersectionObserverEntry) => void;
6 /** How much of the element must be visible, from 0 to 1. */
7 threshold?: number;
8 /** Margin around the viewport, as a CSS margin string. */
9 root_margin?: string;
10 /** Stop observing after the first `on_enter`. */
11 once?: boolean;
12}threshold defaults to 0, root_margin to '0px' and once to true. Set once to false with an on_leave to track an element
going in and out of view, and a root_margin such as '200px' to
start loading a little before it arrives.