export type GoogleId = { initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void renderButton: (el: HTMLElement, o: Record) => void } declare global { interface Window { google?: { accounts: { id: GoogleId } } } } const SCRIPT = 'https://accounts.google.com/gsi/client' let loading: Promise | null = null /** 구글 로그인 스크립트는 한 번만 받는다. 실패하면 다음에 다시 받는다 */ export function loadGoogle(): Promise { if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id) loading ??= new Promise((resolve, reject) => { const s = document.createElement('script') s.src = SCRIPT s.async = true s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing'))) s.onerror = () => { loading = null reject(new Error('gsi load failed')) } document.head.appendChild(s) }) return loading } /** 로그인 안 한 사람은 화면이 한가할 때 스크립트를 미리 받아 둔다. 로그인 창이 올라오는 도중에 스크립트를 실행하느라 화면이 멈추지 않게. 돌려준 함수로 취소 */ export function preloadGoogle(): () => void { const run = () => void loadGoogle().catch((e: unknown) => console.error('[google] preload', e)) if ('requestIdleCallback' in window) { const id = requestIdleCallback(run, { timeout: 4000 }) return () => cancelIdleCallback(id) } const id = setTimeout(run, 2500) return () => clearTimeout(id) }