|
| 1 | +/** |
| 2 | + * Sprite Loader - Dynamically loads and injects SVG sprites into the DOM |
| 3 | + * Uses sprite-manifest.json generated by SvgSpriteWebpackPlugin |
| 4 | + */ |
| 5 | +(function () { |
| 6 | + "use strict"; |
| 7 | + |
| 8 | + // Function to load sprite manifest |
| 9 | + async function loadSpriteManifest() { |
| 10 | + try { |
| 11 | + var response = await fetch("build/sprite-manifest.json"); |
| 12 | + if (!response.ok) { |
| 13 | + throw new Error("Failed to load sprite manifest: " + response.status); |
| 14 | + } |
| 15 | + var manifest = await response.json(); |
| 16 | + return manifest.sprites || []; |
| 17 | + } catch (error) { |
| 18 | + throw new Error("Invalid sprite manifest: " + error.message); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + // Function to load and inject a single sprite |
| 23 | + async function loadSprite(spriteUrl) { |
| 24 | + var response = await fetch(spriteUrl); |
| 25 | + if (!response.ok) { |
| 26 | + throw new Error( |
| 27 | + "Failed to load sprite: " + spriteUrl + " (" + response.status + ")" |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + var svgContent = await response.text(); |
| 32 | + |
| 33 | + // Create a div to hold the sprite |
| 34 | + var spriteContainer = document.createElement("div"); |
| 35 | + spriteContainer.style.display = "none"; |
| 36 | + spriteContainer.innerHTML = svgContent; |
| 37 | + |
| 38 | + // Insert at the beginning of body |
| 39 | + document.body.insertBefore(spriteContainer, document.body.firstChild); |
| 40 | + |
| 41 | + console.log("SVG sprite loaded:", spriteUrl); |
| 42 | + } |
| 43 | + |
| 44 | + // Function to load all sprites |
| 45 | + async function loadAllSprites(spritePaths) { |
| 46 | + var promises = spritePaths.map(function (spritePath) { |
| 47 | + return loadSprite("build/" + spritePath); |
| 48 | + }); |
| 49 | + |
| 50 | + return Promise.all(promises); |
| 51 | + } |
| 52 | + |
| 53 | + // Main function to initialize sprite loading |
| 54 | + async function initSpriteLoader() { |
| 55 | + // Only load if document is ready |
| 56 | + if (document.readyState === "loading") { |
| 57 | + document.addEventListener("DOMContentLoaded", initSpriteLoader); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + console.log("Initializing sprite loader..."); |
| 62 | + |
| 63 | + try { |
| 64 | + var spritePaths = await loadSpriteManifest(); |
| 65 | + console.log("Found", spritePaths.length, "sprite(s) to load"); |
| 66 | + await loadAllSprites(spritePaths); |
| 67 | + console.log("All sprites loaded successfully"); |
| 68 | + } catch (error) { |
| 69 | + console.warn("Sprite loader failed:", error.message); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + // Start the process |
| 74 | + initSpriteLoader(); |
| 75 | +})(); |
0 commit comments