fix: 로그인 창을 처음 열 때 버벅이던 것 줄임 — 구글 로그인 스크립트는 한가할 때 미리 받고, 구글 버튼과 뒤 화면 멈추기는 창이 다 올라온 뒤에
This commit is contained in:
1 parent
7d84226105
commit
7dcd6c6a4c
5 files changed
+65
-36
No files matched your search
@@ -0,0 +1,40 @@
|
||||
export type GoogleId = {
|
||||
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
|
||||
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
|
||||
}
|
||||
declare global {
|
||||
interface Window {
|
||||
google?: { accounts: { id: GoogleId } }
|
||||
}
|
||||
}
|
||||
|
||||
const SCRIPT = 'https://accounts.google.com/gsi/client'
|
||||
let loading: Promise<GoogleId> | null = null
|
||||
|
||||
/** 구글 로그인 스크립트는 한 번만 받는다. 실패하면 다음에 다시 받는다 */
|
||||
export function loadGoogle(): Promise<GoogleId> {
|
||||
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)
|
||||
}
|
||||
Reference in new issue
Block a user