THIRD-PARTY SCRIPT
third-party-script.ts
External script loading with 3 states: loading, ready, error.
StarkWHAT THIS PATTERN TEACHES
How to load external scripts (Google Identity, Stripe.js, analytics SDKs) with a proper 3-state machine. The timeout MUST transition to 'error', not stay in 'loading' — an infinite spinner is worse than an error message.
WHEN TO USE THIS
Any external SDK integration: payment widgets, auth providers, analytics, chat widgets, ad scripts.
AT A GLANCE
type ScriptState = 'loading' | 'ready' | 'error';
function loadScript(src: string) {
const el = document.createElement('script');
el.onload = () => state = 'ready';
el.onerror = () => state = 'error';
}FRAMEWORK IMPLEMENTATIONS
TypeScript
type ScriptState = 'loading' | 'ready' | 'error';
interface ThirdPartyScript {
state: ScriptState;
error: string | null;
}
function loadExternalScript(
src: string,
timeoutMs = 10_000
): ThirdPartyScript {
const script: ThirdPartyScript = {
state: 'loading',
error: null,
};
const el = document.createElement('script');
el.src = src;
el.async = true;