Iconify for Svelte function: loadIcon

This tutorial is part of Iconify for Svelte functions tutorial.

Function loadIcon() retrieves an icon from Iconify API.

It returns Promise instance, making it very easy to use in asynchronous code.

When to use this function:

  • When you need to get icon data inside an asynchronous function.

When not to use this function:

  • To preload multiple icons that you will use later. Use loadIcons() instead.

It is safe to call function multiple times with the same icon name, component will not load icon data from Iconify API twice. If you pass string icon name as parameter, multiple calls of the function will return the same Promise instance.

Usage

Function has the following parameter:

Function returns Promise instance, which returns FullIconifyIcon data for icon on success.

IconifyIconName type

IconifyIconName is a simple object with the following properties, all properties are mandatory:

  • provider, string. API provider. For public Iconify API value is an empty string "".
  • prefix, string. Icon set prefix.
  • name, string. Icon name.

Examples

Using Promise syntax:

import { loadIcon } from '@iconify/svelte';

const iconName = 'mdi:home';
loadIcon(iconName)
   .then((data) => {
       console.log(
           `Icon ${iconName} have been loaded and is ready to be renderered.`
       );
       console.log(data);
   })
   .catch((err) => {
       console.log(`Icon ${iconName} does not exist.`);
   });

Async/await syntax:

import { loadIcon } from '@iconify/svelte';

/**
* Usage example in async function
*/

async function test() {
   try {
       const data = await loadIcon('mdi:home');
       console.log('Loaded home icon!');
   } catch (err) {
       console.error('Failed to load home icon');
   }
}
test();

If you want to load multiple icons, see loadIcons().