You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态添加Vivid图标失效:如何触发v()函数完成SVG转换?

Fixing Dynamic Vivid Icons Not Rendering as 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:

  1. Process the entire document (simple but less efficient)
    If you’re adding icons scattered across the page, you can just re-run the full v() function. This will re-process all elements, including your new dynamic ones:

    v();
    
  2. 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 to v() 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);
    
  3. 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.js script tag, or
  • Wrap your code in a DOMContentLoaded event listener:
    document.addEventListener('DOMContentLoaded', function() {
      // Your dynamic icon code here
    });
    

内容的提问来源于stack exchange,提问作者Dejan Dozet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:58:14