Iconify for Svelte function: iconLoaded
This tutorial is part of Iconify for Svelte functions tutorial.
The function iconLoaded() checks if icon data is available for rendering.
Usage
The function has the following parameter:
- name, string. Icon name.
The function returns boolean value: true if icon data is available, false if icon data is not available.
Example
This example renders fallback snippet while icon is being loaded.
<script lang="ts">
import Icon, { iconLoaded, loadIcons, type IconifyIconLoaderAbort }from '@iconify/svelte';
import{ onDestroy }from 'svelte';
// Icon to render and fallback children
let{ icon, fallback } = $props();
// Icon status and cleanup function
let loaded = $state(false);
let cleanup: IconifyIconLoaderAbort | null = null;
let update = $state(0);
$effect(() =>{
// Mention update to re-run this effect when state changes
update;
// Get icon data
loaded = iconLoaded(icon);
// Cancel previous callback
if (cleanup) {
cleanup();
cleanup = null;
}
// Load icon
if (!loaded) {
cleanup = loadIcons([icon], () => {
// Trigger re-running of code above
update ++;
});
}
})
// Cleanup
onDestroy(() =>{
if (cleanup) {
cleanup();
}
})
</script>
{#if loaded}
<Icon icon={icon} />
{:else}
{@render fallback?.()}
{/if}
Usage example:
<IconWrapper icon="mdi-light:alert">
{#snippet fallback()}
<small>!</small>
{/snippet}
</IconWrapper>
This example uses iconLoaded() to show function, but for this purpose it is better to use getIcon(). See getIcon() documentation for better example.
Legacy
Note: in old versions of component, this function was named iconExists(). It was the same function, but with bad name.
Because of bad name, some developers assumed it checks if icon exists on Iconify API. It does not. All it does is checks component's storage.
To avoid confusion, function was renamed.