fix(#39993): avoid race condition for next/script onReady (#40002)
Fixes #39993. Before the PR: - `next/script` component mount, `useEffect` for `onReady` executes - The script's cacheKey is not added to `LoadCache`, skip `onReady` - The second `useEffect` for `loadScript` executes - The script's cacheKey is added to `LoadCache` even if it might not fully load yet - Because of React's strict mode, `useEffect` for `onReady` executes again - Since the script's cacheKey is in `LoadCache`, `onReady` is called (even when the script is not loaded yet) - After the script is actually loaded, inside the `script.onload` event handler the `onReady` is called again After the PR: - `next/script` component mount, `useEffect` for `onReady` executes - The script's cacheKey is not added to `LoadCache`, `useEffect` skips `onReady` - The second `useEffect` for `loadScript` executes - The script's cacheKey is added to `LoadCache` only if it is an inline script - Because of React's strict mode, `useEffect` for `onReady` executes again - The script is not yet loaded, its cacheKey is not in `LoadCache`, `useEffect` skips `onReady` again - After the script is actually loaded, inside the `script.onload` event handler the `onReady` is finally called In short, the PR resolves a race condition that only occurs under React strict mode (and makes the `next/script` component more concurrent rendering resilient). ## Bug - [x] Related issues linked using `fixes #number` - [x] Integration tests added - [ ] Errors have helpful link attached, see `contributing.md`
Showing
Please
register
or
sign in
to comment