Skip to content

perf(Auth): start loading Google scripts from the page head - #2510

Open
anirudhpv wants to merge 1 commit into
googleanalytics:mainfrom
anirudhpv:perf/early-google-script-loading
Open

anirudhpv wants to merge 1 commit into
googleanalytics:mainfrom
anirudhpv:perf/early-google-script-loading

Conversation

@anirudhpv

Copy link
Copy Markdown

Problem

On every page load the login button and the tools that need the Analytics APIs stay in a loading state for a noticeable time before the signed-in state is known.

Cause

api.js, gsi/client and the Analytics Data/Admin API discovery docs are only requested from onInitialClientRender, i.e. after the JS bundle has downloaded, parsed and React has hydrated. On top of that, the discovery docs are only fetched after both scripts have loaded, so the slower sign-in script also delays them. All of this is sequential.

Fix

  • gatsby-ssr.tsx: add an onRenderBody that injects a small inline loader into <head>. It starts loading api.js and gsi/client immediately, loads the discovery docs as soon as gapi.client is ready, and exposes the promises on window.__googleScripts.
  • gatsby/onInitialClientRender.js: use the preloaded promises when present (falling back to loading the scripts itself if not), fetch the discovery docs without waiting for the sign-in script, and split the code into small helpers (loadGapi, loadGis, restoreToken). The token client setup, stored-token restore and error handling behave as before.

How tested

  • yarn check-types: no new errors (the 3 existing errors on main are unrelated).
  • gatsby build succeeds and the generated HTML contains the loader script in <head>.
  • On a fork deployment, the time until Query Explorer leaves "Checking if you're logged in" dropped from about 4.5s to 1.8s (measured with Playwright). api.js and gsi/client now start loading about 150ms after navigation instead of after hydration.

api.js, gsi/client and the Analytics API discovery docs were only
requested from onInitialClientRender, i.e. after the JS bundle had
downloaded and React had hydrated, so the login check and the first API
calls waited on the whole app first.

Add an inline loader to the document head (onRenderBody) that starts
fetching api.js and gsi/client immediately and loads the discovery docs
as soon as gapi is ready, exposing the promises on
window.__googleScripts. onInitialClientRender picks them up (falling back
to loading the scripts itself) and no longer waits for the sign-in
script before fetching the discovery docs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant