/** * Example usage of the asset caching module in a vanilla JavaScript/TypeScript application * * This example shows how to use the asset cache in a vanilla JS/TS environment * without framework-specific integrations. */ import { AssetLoader, CacheManager, VersionManager, initAssetCache, } from "@shopkit/asset-cache"; /** * Initialize the asset cache */ async function initializeAssetCache() { try { // Initialize the asset cache await initAssetCache({ cacheName: "my-app-cache", enableServiceWorker: true, serviceWorkerPath: "/service-worker.js", debug: true, }); console.log("Asset cache initialized"); } catch (error) { console.error("Failed to initialize asset cache:", error); } } /** * Example of how to preload and cache images */ async function preloadImages(imageUrls: string[]) { try { console.log("Preloading images..."); // Preload each image const preloadPromises = imageUrls.map((url) => AssetLoader.preload(url, { ttl: 7 * 24 * 60 * 60, // Cache for 7 days tags: ["product-images"], }) ); // Wait for all images to be preloaded await Promise.all(preloadPromises); console.log("Images preloaded successfully"); } catch (error) { console.error("Failed to preload images:", error); } } /** * Example of how to load an image with caching */ async function loadCachedImage(imageUrl: string, imgElement: HTMLImageElement) { try { console.log(`Loading image: ${imageUrl}`); // Check if the image is cached const isCached = await AssetLoader.isCached(imageUrl); console.log(`Image is ${isCached ? "cached" : "not cached"}`); // Load the image with caching const result = await AssetLoader.load(imageUrl, { ttl: 7 * 24 * 60 * 60, // Cache for 7 days tags: ["product-images"], }); if (result.success && result.data) { // Create an object URL from the blob const objectUrl = URL.createObjectURL(result.data); // Set the image source imgElement.src = objectUrl; // Clean up the object URL when the image is loaded imgElement.onload = () => { URL.revokeObjectURL(objectUrl); }; console.log( `Image loaded ${result.fromCache ? "from cache" : "from network"}` ); } else { console.error("Failed to load image:", result.error); } } catch (error) { console.error("Error loading image:", error); } } /** * Example of how to load a video with caching */ async function loadCachedVideo( videoUrl: string, videoElement: HTMLVideoElement ) { try { console.log(`Loading video: ${videoUrl}`); // Check if the video is cached const isCached = await AssetLoader.isCached(videoUrl); console.log(`Video is ${isCached ? "cached" : "not cached"}`); // Load the video with caching const result = await AssetLoader.load(videoUrl, { ttl: 7 * 24 * 60 * 60, // Cache for 7 days tags: ["product-videos"], }); if (result.success && result.data) { // Create an object URL from the blob const objectUrl = URL.createObjectURL(result.data); // Set the video source videoElement.src = objectUrl; // Clean up the object URL when the video is loaded videoElement.onloadeddata = () => { console.log( `Video loaded ${result.fromCache ? "from cache" : "from network"}` ); }; } else { console.error("Failed to load video:", result.error); } } catch (error) { console.error("Error loading video:", error); } } /** * Example of how to preload a font */ async function preloadFont(fontUrl: string, fontFamily: string) { try { console.log(`Preloading font: ${fontUrl}`); // Create a font face const fontFace = new FontFace(fontFamily, `url(${fontUrl})`); // Load the font const loadedFont = await fontFace.load(); // Add the font to the document document.fonts.add(loadedFont); // Cache the font await AssetLoader.preload(fontUrl, { ttl: 30 * 24 * 60 * 60, // Cache for 30 days tags: ["fonts"], }); console.log(`Font preloaded successfully`); } catch (error) { console.error("Failed to preload font:", error); } } /** * Example of how to invalidate cached assets */ async function invalidateCachedAssets() { try { console.log("Invalidating cached assets..."); // Invalidate by tag await AssetLoader.invalidateByTag("product-images"); console.log("Product images invalidated"); // Invalidate specific URL await AssetLoader.invalidate("/images/product1.jpg"); console.log("Specific image invalidated"); // Clear the entire cache await CacheManager.clear(); console.log("Cache cleared"); } catch (error) { console.error("Failed to invalidate cached assets:", error); } } /** * Example of how to handle cache invalidation on deployment */ async function handleDeployment() { try { console.log("Handling deployment..."); // Generate a new deployment ID const newDeploymentId = Date.now().toString(36); // Store the previous deployment ID const previousDeploymentId = VersionManager.getDeploymentId(); // Initialize with the new deployment ID VersionManager.init(newDeploymentId); // Invalidate assets from the previous deployment if (previousDeploymentId) { await VersionManager.invalidatePreviousDeployment(previousDeploymentId); } console.log(`Deployed with new version: ${newDeploymentId}`); } catch (error) { console.error("Failed to handle deployment:", error); } } /** * Example usage in a web application */ document.addEventListener("DOMContentLoaded", async () => { // Initialize the asset cache await initializeAssetCache(); // Get elements const productImage = document.getElementById( "product-image" ) as HTMLImageElement; const productVideo = document.getElementById( "product-video" ) as HTMLVideoElement; const preloadButton = document.getElementById("preload-button"); const invalidateButton = document.getElementById("invalidate-button"); // Image and video URLs const imageUrls = [ "/images/product1.jpg", "/images/product2.jpg", "/images/product3.jpg", ]; const videoUrl = "/videos/product-demo.mp4"; // Preload images when the preload button is clicked if (preloadButton) { preloadButton.addEventListener("click", () => { preloadImages(imageUrls); }); } // Invalidate cached assets when the invalidate button is clicked if (invalidateButton) { invalidateButton.addEventListener("click", () => { invalidateCachedAssets(); }); } // Load the product image if (productImage) { loadCachedImage(imageUrls[0], productImage); } // Load the product video if (productVideo) { loadCachedVideo(videoUrl, productVideo); } // Preload a font await preloadFont("/weryze/fonts/product-sans.woff2", "Product Sans"); // Handle deployment (this would typically be done during the build process) // await handleDeployment(); }); /** * Example HTML structure: * * ```html * * * * * * Asset Caching Example * * *

Asset Caching Example

* *
*

Product Image

* Product Image *
* *
*

Product Video

* *
* *
* * *
* * * * * ``` */