Subtlyv0.1.1
Search & loading

nearViewport()

Load content as it nears the screen. Lazy secondary content.

Available in v0.1.1performance.jsPerformance

Try it

Scroll inside the panel until the deferred report comes into view. It initializes once, when it reaches the visible area. The rest of the page stays usable throughout.

Live example
Project overview

Keep scrolling inside this panel to load the secondary report.

Report not initialized

Waiting for the report to enter view.

<div id="your-component">
<div class="deferred-scroll" tabindex="0" role="region" aria-label="Scroll to reveal the deferred report"><div class="deferred-intro"><strong>Project overview</strong><p>Keep scrolling inside this panel to load the secondary report.</p><span class="scroll-cue" aria-hidden="true">⋮</span></div><div data-deferred class="data-preview"><strong data-title>Report not initialized</strong><div class="report-bars" aria-hidden="true" hidden><i></i><i></i><i></i><i></i><i></i></div></div></div><p class="demo-status" role="status">Waiting for the report to enter view.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  return kit.nearViewport(el.querySelector('[data-deferred]'), () => {
            el.querySelector('[data-title]').textContent = 'Report initialized';
            el.querySelector('.report-bars').hidden = false;
            status('Report initialized once when it entered the visible region.');
          }, { rootMargin: '0px' });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

API and lifecycle

Observe an element and run initialize() once it approaches the viewport. rootMargin defaults to 200px. The observer disconnects after initialization; when IntersectionObserver is unavailable, initialization runs immediately.

Interface
element, initialize, rootMargin; returns cleanup.
Lifecycle
The returned cleanup disconnects observation before initialization. If initialize creates listeners or widgets, manage those resources with their own cleanup.

Accessibility and safety

Implementation notes

Essential content must not depend on intersection observation.

Use for secondary content. Essential text, navigation and keyboard access must not depend on the observer running.

What to check

Scroll the element into view and verify initialization happens once. Also test removing the element before intersection and the observer-free fallback.

View documented module source
/** In-memory stale-while-revalidate for non-sensitive GET data.
 * read(key, fetcher, onValue) delivers cached data first, then fresh data.
 * Deduplicates requests per key. Scope instance to user/session; clear on
 * logout. Fetcher must reject on HTTP errors. No persistent storage. */
export function staleCache({ttl=30000,max=50}={}) {
    const cache=new Map(),pending=new Map();let generation=0;
    async function read(key,fetcher,onValue) {
        const epoch=generation, cached=cache.get(key);
        if(cached){onValue?.(cached.value,{stale:Date.now()-cached.at>=ttl});if(Date.now()-cached.at<ttl)return cached.value;}
        if(!pending.has(key)) {
            const promise=Promise.resolve().then(fetcher).then(value=>{if(epoch===generation){cache.delete(key);cache.set(key,{value,at:Date.now()});while(cache.size>max)cache.delete(cache.keys().next().value);}return value;}).finally(()=>{if(pending.get(key)===promise)pending.delete(key);});pending.set(key,promise);
        }
        const value=await pending.get(key);if(epoch===generation)onValue?.(value,{stale:false});return epoch===generation?value:undefined;
    }
    return {read,clear(){generation++;cache.clear();pending.clear();}};
}

/** Lazy initialize secondary content once it approaches the viewport.
 * Essential content should not depend on intersection observation. */
export function nearViewport(element, initialize, {rootMargin='200px'}={}) {
    if(!('IntersectionObserver' in globalThis)){initialize();return ()=>{};}
    const observer=new IntersectionObserver(entries=>{if(entries.some(e=>e.isIntersecting)){observer.disconnect();initialize();}},{rootMargin});observer.observe(element);return ()=>observer.disconnect();
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close