Skip to content

Utilities

The theme extensions provide several utility functions to help with common development tasks.

debounce

A promise-based debounce function with built-in error handling.

Features:

  • Returns a Promise that resolves with the callback result
  • Handles errors gracefully with Promise rejection
  • TypeScript-friendly with proper type inference
  • Cancels previous calls when new ones are made

Usage:

ts
import { debounce } from 'wly-statamic-theme-extensions';

const search = debounce(async (query: string) => {
    const response = await fetch(`/api/search?q=${query}`);
    return response.json();
}, 300);

// Use with async/await
try {
    const results = await search('my query');
    console.log(results);
} catch (error) {
    console.error('Search failed:', error);
}

// Or with promises
search('another query')
    .then(results => console.log(results))
    .catch(error => console.error(error));

onReady

A DOM ready callback system that ensures code executes at the appropriate document state.

Mostly Unnecessary with Modern Module Scripts

If you're using type="module" scripts (which you should be), you don't need onReady in most cases. Module scripts automatically execute after the DOM is parsed, making this utility redundant.

See the Getting Started guide for optimal script placement.

When you might still need this:

  • You need to wait for all resources (images, styles) to load using 'complete' state
  • You're working with legacy non-module scripts
  • You're writing library code that must support various loading scenarios
  • Dynamic script loading at unpredictable times

Usage:

ts
import { onReady } from 'wly-statamic-theme-extensions';

// Default: runs at 'interactive' state (DOM parsed, DOMContentLoaded)
// Note: Module scripts already run at this state by default
onReady(() => {
    console.log('DOM is ready!');
    // Initialize your components here
});

// Wait for all resources including images - useful for layout calculations
onReady(() => {
    // Measure image dimensions, work with fully loaded content
    calculateLayout();
}, 'complete');

Parameters:

  • callback: () => any - Function to execute when ready
  • readyState: 'interactive' | 'complete' - When to execute (default: 'interactive')
    • 'interactive': Executes after DOM is parsed (DOMContentLoaded) - images may still be loading
    • 'complete': Executes after all resources including images and stylesheets are loaded

Module Scripts and DOM Ready State

When using type="module" scripts, they automatically execute at the 'interactive' state (after DOM is fully parsed). This means wrapping your code in onReady() with the default 'interactive' parameter provides no additional benefit.

The only time you'd need onReady with module scripts is when you specifically need the 'complete' state to ensure all images and resources are loaded.