Subtlyv0.1.1
Search & loading

staleCache()

Show previous results while refreshing. Cached GET data.

Available in v0.1.1performance.jsPerformance

Try it

Load the project summary twice within two seconds. The second read uses the cache. Wait longer and load again: the previous version appears while a fresh one is requested.

Live example
Project summaryNo summary loaded

Cache is empty.

Server reads 0Cache lifetime 2 seconds

Ready to load.

<div id="your-component">
<div class="data-preview"><span class="muted">Project summary</span><strong data-value>No summary loaded</strong><p data-freshness>Cache is empty.</p></div><button>Load project summary</button><div class="demo-metrics"><span>Server reads <strong data-count>0</strong></span><span>Cache lifetime <strong>2 seconds</strong></span></div><p class="demo-status" role="status">Ready to load.</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() {
  const cache = kit.staleCache({ ttl: 2000 });
          let calls = 0;
          el.querySelector('button').addEventListener('click', async () => {
            status('Reading project summary…');
            try {
              await cache.read('project-summary', async () => {
                el.querySelector('[data-count]').textContent = String(++calls);
                await wait(800);
                return 'Website redesign · version ' + calls;
              }, (value, meta) => {
                el.querySelector('[data-value]').textContent = value;
                el.querySelector('[data-freshness]').textContent = meta.stale ? 'Cached copy visible. Refreshing…' : 'Current copy. Available from cache for 2 seconds.';
                status(meta.stale ? 'Showing previous data while a new version loads.' : 'Summary ready.');
              });
            } catch { status('Could not refresh. Try again.'); }
          }, { signal });
          return () => cache.clear();
}
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

Create a cache for non-sensitive reads. read(key, fetcher, onValue) delivers cached data first, then refreshes stale data. Concurrent reads for the same key share pending work. Defaults: 30-second TTL, 50 entries.

Interface
ttl, max; read/clear.
Lifecycle
clear() empties the cache and invalidates pending delivery into the old cache generation. Scope the instance to one user/session and clear on logout. Data is not persisted to disk.

Accessibility and safety

Implementation notes

Use only non-sensitive reads, scope to user/session, and clear on logout.

The fetcher must reject on HTTP errors. Distinguish stale data from a fresh response where that affects a decision, and avoid caching sensitive results.

What to check

Load within the TTL, then after it expires. Verify cached data can appear before the refresh, failures are handled, and clearing prevents old results leaking into a new session.

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