Quickstart - Svelte Shields
Svelte Shields is a collection of Shields badges for Svelte Runes.
Installation #
# install svelte 5
npx sv create my-project
# install svelte-shields
pnpm i -D svelte-shields
Basic usage #
<script lang="ts">
import { NpmVersion, type NpmVersionPropsType } from 'svelte-shields';
const basic: NpmVersionPropsType = {
packageName: 'svelte-shields',
logo: 'svelte',
label: 'Svelte Shields'
};
</script>
<NpmVersion {...basic} />
Handling Badge Load Failures #
Badges may fail to load due to network issues or service downtime. Here's how to add safeguards to gracefully handle these scenarios:
Loading badge...
<script lang="ts">
import { NpmAuthorDownload, type NpmAuthorDownloadPropsType } from 'svelte-shields';
import { onMount } from 'svelte';
import { browser } from '$app/environment';
const weekly: NpmAuthorDownloadPropsType = {
author: 'shinichiokada',
style: 'for-the-badge'
};
let badgeLoaded = $state(false);
let isChecking = $state(true);
/**
* Check if badge loads successfully
* Prevents race conditions by ensuring only one resolution occurs
*/
async function checkBadgeLoad(url: string): Promise<boolean> {
if (!browser) return false;
return new Promise((resolve) => {
const img = new Image();
let timeoutId: ReturnType<typeof setTimeout>;
let settled = false;
const finish = (ok: boolean) => {
if (settled) return;
settled = true;
clearTimeout(timeoutId);
resolve(ok);
};
img.onload = () => {
finish(img.naturalWidth > 50 && img.naturalHeight > 10);
};
img.onerror = () => {
finish(false);
};
timeoutId = setTimeout(() => finish(false), 5000);
img.src = url;
});
}
onMount(async () => {
if (!browser) {
isChecking = false;
return;
}
const url = `https://img.shields.io/npm-stat/dw/shinichiokada?style=for-the-badge`;
badgeLoaded = await checkBadgeLoad(url);
isChecking = false;
});
</script>
{#if isChecking}
<p class="text-gray-500">Loading badge...</p>
{:else if badgeLoaded}
<NpmAuthorDownload {...weekly} />
{:else}
<p class="text-gray-500">Badge temporarily unavailable</p>
{/if}
This pattern allows you to detect when badges fail to load and provide appropriate fallback UI, improving the user experience when external services are unavailable.
Key Features #
- ✅ Simple, presentational components with minimal dependencies
- ✅ Full TypeScript support with comprehensive prop types
- ✅ Supports all shields.io badge styles and customization options
- ✅ Browser-native error handling - leverage standard
imgbehavior - ✅ Flexible - implement your own error handling strategies