html★ exposes a simple JavaScript API for programmatic control.
Global Object
When loaded via script tag, html★ exposes the htmlstar global:
console.log(htmlstar.version); // "0.5.0"/code-block<p>When using ES modules:</p><code-block language="javascript">import htmlstar from 'html-star';// orimport { init, resolve, swap } from 'html-star';
Core Functions
htmlstar.init(root)
Initialize html★ on a DOM subtree. Called automatically on page load and after swaps.
<h3>htmlstar.resolve(element, attribute)</h3><p>Resolve an attribute value by walking up the DOM tree.</p><code-block language="javascript">const link = document.querySelector('a');const target = htmlstar.resolve(link, 'target'); // e.g., "#main"const swap = htmlstar.resolve(link, 'swap'); // e.g., "inner"/code-block<h3>htmlstar.hasAttr(element, attribute)</h3><p>Check if an element has a truthy attribute value.</p><code-block language="javascript">if (htmlstar.hasAttr(link, 'push')) { console.log('This link pushes to history');}
htmlstar.resolveAll(element)
Get all resolved attributes for an element.
const attrs = htmlstar.resolveAll(link);// { target: "#main", swap: "inner", push: "", transitions: "true" }/code-block<h2>Swap Function</h2><h3>htmlstar.swap(target, html, strategy)</h3><p>Swap content into an element. Returns a Promise.</p><code-block language="javascript">const target = document.getElementById('content');await htmlstar.swap(target, '<p>New content</p>', 'inner'); // With View Transitions (if supported)await htmlstar.swap(target, html, 'append');
Request Functions
htmlstar.getURL(element)
Get the URL from an element.
const url = htmlstar.getURL(link); // From href, action, or data-href/code-block<h3>htmlstar.getMethod(element)</h3><p>Get the HTTP method for an element.</p><code-block language="javascript">const method = htmlstar.getMethod(form); // "POST"/code-block<h3>htmlstar.shouldSkip(element, url)</h3><p>Check if an element should be skipped by htmlstar.</p><code-block language="javascript">if (htmlstar.shouldSkip(link, link.href)) { console.log('External link or opt-out');}
Persistence Functions
htmlstar.clearPersisted(element)
Clear the persisted value for an element.
const input = document.querySelector('[data-persist]');htmlstar.clearPersisted(input);
htmlstar.clearPersistedByPrefix(prefix, scope)
Clear all persisted values matching a prefix.
<h2>SSE Functions</h2><h3>htmlstar.closeSSE(element)</h3><p>Close an SSE connection for an element.</p><code-block language="javascript">const feed = document.querySelector('[data-sse]');htmlstar.closeSSE(feed);
htmlstar.closeAllSSE()
Close all SSE connections.
htmlstar.closeAllSSE();
htmlstar.stopPolling(element)
Stop polling for an element.
const status = document.querySelector('[data-poll]');htmlstar.stopPolling(status);
Cache Functions
htmlstar.clearCache()
Clear the entire response cache (memory and sessionStorage).
htmlstar.clearCache();
htmlstar.getCacheStats()
Get cache statistics.
const stats = htmlstar.getCacheStats();console.log(stats.size); // number of cached entriesconsole.log(stats.keys); // array of cache keys (e.g., ["GET:/api/users"])/code-block<h3>htmlstar.invalidateCacheByPattern(pattern)</h3><p>Invalidate all cache entries whose URL matches a regex pattern.</p><code-block language="javascript" Invalidate="" all="" api="" products="" entries="" htmlstar.invalidateCacheByPattern('="" products');="" API="" cache="" .*');<="" code-block=""><p>The pattern is converted to a <code>RegExp</code> if passed as a string. Also scans sessionStorage for persistent cache entries.</p><h2>Lifecycle Events</h2><p>html★ dispatches Custom Events at key points during the request lifecycle. All request events (<code>htmlstar:request-*</code>) are dispatched on the triggering element with <code>bubbles: true</code> and <code>composed: true</code>, so they propagate up through the DOM and can be caught on any ancestor element.</p><h3>htmlstar:request-start</h3><p>Fired when a request begins, before the fetch is made.</p><p><strong>Detail properties:</strong> <code>id</code>, <code>url</code>, <code>method</code>, <code>target</code>, <code>swap</code>, <code>select</code>, <code>element</code></p><code-block language="javascript">document.addEventListener('htmlstar:request-start', (e) => { console.log('Request started:', e.detail.url);});
htmlstar:request-end
Fired when a request completes successfully, after the content has been swapped in and history updated.
Detail properties: id, url, method, target, swap, select, element, status, ok, fromCache
The fromCache property is true when the response was served from cache rather than a live fetch. The status and ok properties reflect the HTTP response (these are undefined for cached responses).
htmlstar:request-error
Fired when a request fails (network error, non-OK HTTP status, etc.).
Detail properties: id, url, method, target, swap, select, element, error
document.addEventListener('htmlstar:request-error', (e) => { reportError(e.detail.error);});
htmlstar:request-abort
Fired when a request is aborted, for example by queue control replacing an in-flight request with a newer one.
Detail properties: id, url, method, target, swap, select, element
htmlstar:navigated
Fired on window after history is updated following a successful request. Useful for updating active navigation state or other UI that depends on the current URL.
Detail properties: url, target, swap
window.addEventListener('htmlstar:navigated', (e) => { console.log('Navigated to:', e.detail.url);});
Catching Events on Parent Elements
Because the request events bubble, you can listen on a parent element to handle events from all html★-enhanced elements within it:
document.getElementById('app').addEventListener('htmlstar:request-start', (e) => { console.log('A request started from:', e.detail.element);});
Utility Functions
htmlstar.debounce(fn, ms)
Create a debounced function.
const debouncedSearch = htmlstar.debounce((query) => { console.log('Searching for:', query);}, 300); input.addEventListener('input', (e) => debouncedSearch(e.target.value));
htmlstar.throttle(fn, ms)
Create a throttled function. Executes immediately on first call, then at most once per interval.
const throttledScroll = htmlstar.throttle(() => { console.log('Scroll position:', window.scrollY);}, 200); window.addEventListener('scroll', throttledScroll);
Configuration
htmlstar.getConfig()
Get the current configuration.
const config = htmlstar.getConfig();// { defaults: {...}, selectors: {...} }/code-block<h3>htmlstar.clearConfigCache()</h3><p>Clear the cached configuration (useful after dynamic config changes).</p><code-block language="javascript">htmlstar.clearConfigCache();
Constants
htmlstar.DEFAULTS
The built-in default values (read-only).
console.log(htmlstar.DEFAULTS);// { swap: "inner", transitions: "true", debounce: 300 }/code-block<h3>htmlstar.version</h3><p>The library version.</p><code-block language="javascript">console.log(htmlstar.version); // "0.5.0"/code-block