-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
fix(react-router): inject head() src scripts once, not on every navigation #8227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+115
−1
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
packages/react-router/tests/head-script-src-navigation.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { createPortal } from 'react-dom' | ||
| import { | ||
| cleanup, | ||
| fireEvent, | ||
| render, | ||
| screen, | ||
| waitFor, | ||
| } from '@testing-library/react' | ||
| import { afterEach, expect, test, vi } from 'vitest' | ||
| import { | ||
| HeadContent, | ||
| Link, | ||
| Outlet, | ||
| RouterProvider, | ||
| createMemoryHistory, | ||
| createRootRoute, | ||
| createRoute, | ||
| createRouter, | ||
| } from '../src' | ||
|
|
||
| afterEach(() => { | ||
| cleanup() | ||
| document.head.innerHTML = '' | ||
| vi.restoreAllMocks() | ||
| }) | ||
|
|
||
| // A head() script with `src` must be injected (and therefore executed) exactly | ||
| // once. Before the fix, the injection effect keyed off the `attrs` object | ||
| // identity, which changes on every navigation that rebuilds head tags - so | ||
| // the script was removed and re-injected (re-executed) on every navigation. | ||
| test('head() scripts with src are not re-injected on client-side navigations', async () => { | ||
| const rootRoute = createRootRoute({ | ||
| head: () => ({ | ||
| scripts: [{ src: '/track-test.js' }], | ||
| }), | ||
| component: () => ( | ||
| <> | ||
| {createPortal(<HeadContent />, document.head)} | ||
| <Link to="/">index</Link> | ||
| <Link to="/pool/$id" params={{ id: '123' }}> | ||
| pool | ||
| </Link> | ||
| <Outlet /> | ||
| </> | ||
| ), | ||
| }) | ||
| const indexRoute = createRoute({ | ||
| getParentRoute: () => rootRoute, | ||
| path: '/', | ||
| head: () => ({ meta: [{ title: 'Home Page' }] }), | ||
| component: () => <div data-testid="index-page">index</div>, | ||
| }) | ||
| const poolRoute = createRoute({ | ||
| getParentRoute: () => rootRoute, | ||
| path: '/pool/$id', | ||
| head: () => ({ meta: [{ title: 'Pool Detail' }] }), | ||
| component: () => <div data-testid="pool-page">pool</div>, | ||
| }) | ||
| const router = createRouter({ | ||
| routeTree: rootRoute.addChildren([indexRoute, poolRoute]), | ||
| history: createMemoryHistory({ initialEntries: ['/'] }), | ||
| }) | ||
|
|
||
| const injections: Array<HTMLScriptElement> = [] | ||
| const removals: Array<HTMLScriptElement> = [] | ||
| const originalAppendChild = document.head.appendChild.bind(document.head) | ||
| vi.spyOn(document.head, 'appendChild').mockImplementation((node: any) => { | ||
| if ( | ||
| node instanceof HTMLScriptElement && | ||
| node.getAttribute('src') === '/track-test.js' | ||
| ) { | ||
| injections.push(node) | ||
| } | ||
| return originalAppendChild(node) | ||
| }) | ||
| vi.spyOn(HTMLScriptElement.prototype, 'remove').mockImplementation( | ||
| function (this: HTMLScriptElement) { | ||
| if (this.getAttribute('src') === '/track-test.js') { | ||
| removals.push(this) | ||
| } | ||
| // Element.prototype.remove | ||
| this.parentNode?.removeChild(this) | ||
| }, | ||
| ) | ||
|
|
||
| render(<RouterProvider router={router} />) | ||
| expect(await screen.findByTestId('index-page')).toBeInTheDocument() | ||
| await waitFor(() => expect(document.title).toBe('Home Page')) | ||
| expect(injections).toHaveLength(1) | ||
|
|
||
| fireEvent.click(screen.getByRole('link', { name: 'pool' })) | ||
| expect(await screen.findByTestId('pool-page')).toBeInTheDocument() | ||
| await waitFor(() => expect(document.title).toBe('Pool Detail')) | ||
|
|
||
| fireEvent.click(screen.getByRole('link', { name: 'index' })) | ||
| expect(await screen.findByTestId('index-page')).toBeInTheDocument() | ||
| await waitFor(() => expect(document.title).toBe('Home Page')) | ||
|
|
||
| // Every re-injection re-executes the script in a real browser. | ||
| expect(injections).toHaveLength(1) | ||
| expect(removals).toHaveLength(0) | ||
| expect( | ||
| document.head.querySelectorAll('script[src="/track-test.js"]'), | ||
| ).toHaveLength(1) | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: TanStack/router
Length of output: 22439
🤖 get_repo_knowledge executed:
get_repo_knowledge TanStack/router /tmp/coderabbit-repo-knowledge/tanstack-router-7628dab7/learningsLength of output: 11911
🏁 Script executed:
Repository: TanStack/router
Length of output: 48693
Canonicalize script identity before serializing attributes.
HeadContentusesJSON.stringify(tag)as theAssetkey, whileAssetusesJSON.stringify(attrs ?? null)for its effect dependency. Equivalent script attributes with different property order change both keys. React can remountAsset, remove the existing script during cleanup, and inject it again.Use one canonical, sorted representation for both keys. Add a navigation test that reverses equivalent script attribute order between renders.
🤖 Prompt for AI Agents