动态添加Vivid图标失效:如何触发v()函数完成SVG转换?
Hey there! I’ve dealt with exactly this kind of issue before—icon libraries that only process elements on the initial page load, leaving dynamically added icons stuck as plain <i> tags. Let’s get those Vivid Icons rendering properly.
Why This Happens
The v() function from vivid-icons.js runs automatically when the page first loads, converting all existing <i data-vi="..."> elements to SVG. But any icons you add later (via JavaScript, AJAX, etc.) don’t get picked up by that initial run—you need to manually trigger the conversion for these new elements.
How to Trigger the v() Function for Dynamic Icons
Here are a few straightforward ways to handle this:
Process the entire document (simple but less efficient)
If you’re adding icons scattered across the page, you can just re-run the fullv()function. This will re-process all elements, including your new dynamic ones:v();Target a specific container (better for performance)
If you’re adding icons to a specific part of the page (like a modal, sidebar, or dynamically loaded section), pass that container element tov()to only process elements inside it. This avoids re-scanning the entire DOM:// Get your target container const targetContainer = document.getElementById('dynamic-content-area'); // Add your dynamic icon const newIcon = document.createElement('i'); newIcon.setAttribute('data-vi', 'bag'); targetContainer.appendChild(newIcon); // Process only the container (and its children) v(targetContainer);Wrap it in a reusable function
For convenience, you can create a small helper function to render icons wherever you need them:function renderDynamicVividIcons(targetElement = document) { // Make sure v() is available before calling if (typeof v === 'function') { v(targetElement); } } // Usage example: After adding an icon to a modal const modal = document.getElementById('my-modal'); const cartIcon = document.createElement('i'); cartIcon.setAttribute('data-vi', 'cart'); modal.appendChild(cartIcon); renderDynamicVividIcons(modal);
Important Note
Make sure vivid-icons.js has fully loaded before you call v(). If you’re running your dynamic code early (like before the script loads), you’ll get a "v is not defined" error. To avoid this, either:
- Place your dynamic code after the
vivid-icons.jsscript tag, or - Wrap your code in a
DOMContentLoadedevent listener:document.addEventListener('DOMContentLoaded', function() { // Your dynamic icon code here });
内容的提问来源于stack exchange,提问作者Dejan Dozet

