Custom icon loaders
This tutorial is part of Iconify for Svelte tutorial.
Functions setCustomIconLoader() and setCustomIconsLoader() are used to define custom icon loaders.
What is it for?
- To load icon data from custom sources.
- To modify icons, such as changing color or stroke width.
Usage
Both functions have the same parameters, except for type of callback:
- callback, function. Callback that loads icons, can be synchronous or asynchronous function.
- prefix, string. Icon set prefix.
- provider, string. Icon set provider, optional.
Callback is a function that loads icon data.
Both synchronous and asynchronous (returns Promise instance) callbacks are supported.
Callbacks for both functions have similar parameters.
Parameters for setCustomIconLoader():
- name, string. Icon name.
- prefix, string. Icon set prefix.
- provider, string. Icon set provider.
Order of parameters is intentional: from most important to least important. If you have set loader for one prefix, you most likely only need name parameter.
The callback returns icon data as IconifyIcon or null on failure (or Promise of those types).
Callback for setCustomIconsLoader() is almost identical, except:
- First parameter is an array of icon names: string[].
- Callback returns an icon set as IconifyJSON or null on failure (or Promise of those types).
Example
import { setCustomIconLoader, loadIcon } from "@iconify/svelte";
// Creates icon set "tabler-thin" that loads icons from Tabler Icons and makes them thinner
// Then you can use "tabler:angle" to render icon with default stroke, or "tabler-thin:angle" to render thinner icon
setCustomIconLoader(async (name) => {
const data = await loadIcon(`tabler:${name}`);
return data
? {
...data,
body: data.body.replaceAll('stroke-width="2"', 'stroke-width="1"'),
}
: null;
}, "tabler-thin");
// Fetches icon from custom server
// Icon data must be in IconifyIcon format
setCustomIconLoader(async (name) => {
const response = await fetch(`https://example.com/icons/${name}.json`);
if (!response.ok) {
return null;
}
return await response.json();
}, "custom-server");
Make sure loader is set before any icons are rendered, otherwise component might attempt to load icon from API and fail to render it.