CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-inlinesvg

An SVG loader for React that enables inline SVG rendering with caching and preprocessing capabilities

Pending
Overview
Eval results
Files

caching.mddocs/

Persistent Caching

Advanced caching functionality using the browser's Cache API for persistent SVG storage across browser sessions. This enables faster loading times and offline support for cached SVG content.

Capabilities

Cache Provider Setup

Enables persistent caching by wrapping your application with the cache provider. This activates browser Cache API integration for all InlineSVG components.

/**
 * Provider component that enables persistent SVG caching using browser Cache API
 * @param children - React components to wrap with cache context
 * @param name - Custom cache name (default: 'react-inlinesvg')
 */
declare const CacheProvider: React.FC<{
  children: React.ReactNode;
  name?: string;
}>;

Usage Example:

import { createRoot } from "react-dom/client";
import CacheProvider from "react-inlinesvg/provider";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  <CacheProvider name="my-app-svgs">
    <App />
  </CacheProvider>
);

Cache Store Access

Direct access to the global cache store for advanced cache management and introspection.

import { cacheStore } from "react-inlinesvg";

/**
 * Global cache store instance with both in-memory and persistent storage
 */
interface CacheStore {
  /** Cache initialization status - false until Cache API is ready */
  readonly isReady: boolean;
  
  /**
   * Register callback for cache ready state
   * @param callback - Function to call when cache is ready
   */
  onReady(callback: () => void): void;
  
  /**
   * Retrieve SVG content from cache or fetch if not cached
   * @param url - SVG URL to retrieve
   * @param fetchOptions - Optional fetch configuration
   * @returns Promise resolving to SVG content string
   */
  get(url: string, fetchOptions?: RequestInit): Promise<string>;
  
  /**
   * Store SVG content in cache
   * @param url - URL key for the cached content
   * @param data - Storage item with content and status
   */
  set(url: string, data: StorageItem): void;
  
  /**
   * Check if URL is cached and successfully loaded
   * @param url - URL to check
   * @returns True if URL is cached with 'loaded' status
   */
  isCached(url: string): boolean;
  
  /**
   * Get all cached URLs
   * @returns Array of cached URL strings
   */
  keys(): string[];
  
  /**
   * Get all cache entries as key-value pairs
   * @returns Array of objects with URL keys and StorageItem values
   */
  data(): Array<Record<string, StorageItem>>;
  
  /**
   * Remove specific URL from cache (both memory and persistent)
   * @param url - URL to remove from cache
   */
  delete(url: string): Promise<void>;
  
  /**
   * Clear all cached content (both memory and persistent)
   */
  clear(): Promise<void>;
}

interface StorageItem {
  /** SVG content as string */
  content: string;
  /** Current loading/processing status */
  status: Status;
}

type Status = 'idle' | 'loading' | 'loaded' | 'failed' | 'ready' | 'unsupported';

Usage Examples:

import { cacheStore } from "react-inlinesvg";

// Wait for cache to be ready
cacheStore.onReady(() => {
  console.log("Cache is ready");
});

// Check if URL is cached
if (cacheStore.isCached("https://example.com/icon.svg")) {
  console.log("Icon is already cached");
}

// Get cache statistics
console.log(`Cached URLs: ${cacheStore.keys().length}`);
console.log("Cache data:", cacheStore.data());

// Clear cache on user logout
async function clearUserSession() {
  await cacheStore.clear();
  console.log("Cache cleared");
}

// Remove specific cached item
async function removeCachedIcon(url: string) {
  await cacheStore.delete(url);
  console.log(`Removed ${url} from cache`);
}

Global Window Configuration

Browser environment configuration for cache behavior, set via window globals before components initialize. These globals are automatically detected when using CacheProvider.

/**
 * Global window interface extensions for cache configuration
 */
declare global {
  interface Window {
    /** Custom cache name for browser Cache API storage */
    REACT_INLINESVG_CACHE_NAME?: string;
    /** Enable persistent caching using browser Cache API */
    REACT_INLINESVG_PERSISTENT_CACHE?: boolean;
  }
}

Configuration Example:

// Configure before importing react-inlinesvg
if (typeof window !== 'undefined') {
  window.REACT_INLINESVG_CACHE_NAME = 'my-custom-cache';
  window.REACT_INLINESVG_PERSISTENT_CACHE = true;
}

import InlineSVG from "react-inlinesvg";

Caching Behavior

Automatic Caching

By default, all SVG requests are cached in memory when cacheRequests={true} (default). This provides immediate performance benefits for repeated SVG usage within a session.

Persistent Storage

When CacheProvider is used or REACT_INLINESVG_PERSISTENT_CACHE is enabled:

  1. Cache API Detection: Checks for browser Cache API support
  2. Cache Opening: Opens named cache storage
  3. Request Interception: Intercepts SVG fetch requests
  4. Storage: Stores successful responses in both memory and persistent cache
  5. Retrieval: Serves from persistent cache on subsequent visits

Cache Limitations

  • Browser Support: Requires browsers with Cache API support (modern browsers)
  • Storage Quotas: Subject to browser storage limitations
  • HTTPS Requirement: Cache API typically requires HTTPS in production
  • Cache Eviction: Browsers may evict cached content under storage pressure

Cache Strategy

  1. Check Memory: First checks in-memory cache for immediate access
  2. Check Persistent: Falls back to persistent cache if memory miss
  3. Network Fetch: Fetches from network if not in any cache
  4. Dual Storage: Stores successful fetches in both memory and persistent cache
  5. Error Handling: Gracefully falls back to memory-only if persistent cache fails

Install with Tessl CLI

npx tessl i tessl/npm-react-inlinesvg

docs

caching.md

index.md

tile.json