简体   繁体   中英

Load external SVG icons into vanilla JavaScript code

I am using the OpenWeather API to display the current and five day forecast on my client's website.

I have some custom SVG icons that I want to use instead of the icons provided by OpenWeather. I have implemented the following switch statement to display a different icon depending on the weather condition.

let dailyCondition = value.weather[0].description;
let dailyCondtionIcon = "";
    
switch (dailyCondition) {
  case "clear sky":
    dailyConditionIcon = `<svg>icon</svg>`;
    break;
  case "few clouds":
    dailyConditionIcon = `<svg>icon</svg>`;
    break;
  case "thunderstorm":
    dailyConditionIcon = `<svg>icon</svg>`;
    break;
  case "light rain":
    dailyConditionIcon = `<svg>icon</svg>`;
    break;
}

Accessing the icons from template literal code works, but with lots of weather conditions in the switch statement, the code is very bloated. I would like to have the SVG icons stored in an external file and loaded from there.

How would I go about loading the external SVG icons into my vanilla JavaScript file?

If you prefer external svg files you could load them in a <use> element.

See also SVG use with External Source

You can combine all svg icons to a single sprite/asset library svg file and then loading each icon individually by a fragment identifier:

You js definitions might look something like this:

dailyConditionIcon = '<svg class="svgInline" fill="red" ><use href="sprite.svg#circle" /></svg>'

 .svgAssets{ display:none }.svgInline{ display:inline-block; width:1em; height:1em; font-size:32px; }
 <.-- this would be the content of your "sprite:svg" --> <svg class="svgAssets" xmlns="http.//www.w3.org/2000/svg"> <symbol viewBox="0 0 100 100" id="circle"> <circle cx="50%" cy="50%" r="50%"></circle> </symbol> <symbol viewBox="0 0 100 100" id="rect"> <rect x="0" y="0" width="100" height="100"></rect> </symbol> <symbol viewBox="0 0 100 100" id="rectFixedStyle"> <rect x="0" y="0" width="100" height="100" fill="#ccc"></rect> </symbol> </svg> <.-- for demonstration the filenames are dropped. The href of a hosted version would be eg <use href="sprite.svg#circle" /> --> <p> <svg class="svgInline" fill="red" > <use href="#circle" /> </svg> <svg class="svgInline" fill="green" > <use href="#rect" /> </svg> <svg class="svgInline" fill="green" > <use href="#rectFixedStyle" /> </svg> </p>

As you can see you also have some styling abilities like changing fill color.
However the styling options are limited (compared to fully inlined svg) and also depend on your svg structure:
Eg Styles previously definded in your svg elements can't be overriden by a style set in use/svg tag.

For sprite creation I used: svgsprit.es

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM