|
7 | 7 | router, |
8 | 8 | setupProgress, |
9 | 9 | } from '@inertiajs/core' |
10 | | -import { ReactElement, createElement } from 'react' |
| 10 | +import { Fragment, ReactElement, createElement } from 'react' |
11 | 11 | import { renderToString } from 'react-dom/server' |
12 | 12 | import App, { InertiaAppProps, type InertiaApp } from './App' |
13 | 13 | import { config } from './index' |
@@ -61,8 +61,13 @@ export default async function createInertiaApp<SharedProps extends PageProps = P |
61 | 61 | config.replace(defaults) |
62 | 62 |
|
63 | 63 | const isServer = typeof window === 'undefined' |
| 64 | + const useScriptElementForInitialPage = config.get('future.useScriptElementForInitialPage') |
64 | 65 | const el = isServer ? null : document.getElementById(id) |
65 | | - const initialPage = page || JSON.parse(el?.dataset.page || '{}') |
| 66 | + const elPage = |
| 67 | + isServer || !useScriptElementForInitialPage |
| 68 | + ? null |
| 69 | + : document.querySelector(`script[data-page="${id}"][type="application/json"]`) |
| 70 | + const initialPage = page || JSON.parse(elPage?.textContent || el?.dataset.page || '{}') |
66 | 71 |
|
67 | 72 | // @ts-expect-error - This can be improved once we remove the 'unknown' type from the resolver... |
68 | 73 | const resolveComponent = (name) => Promise.resolve(resolve(name)).then((module) => module.default || module) |
@@ -104,16 +109,31 @@ export default async function createInertiaApp<SharedProps extends PageProps = P |
104 | 109 | } |
105 | 110 |
|
106 | 111 | if (isServer && render) { |
107 | | - const body = await render( |
108 | | - createElement( |
109 | | - 'div', |
110 | | - { |
111 | | - id, |
112 | | - 'data-page': JSON.stringify(initialPage), |
113 | | - }, |
114 | | - reactApp as ReactElement, |
115 | | - ), |
116 | | - ) |
| 112 | + const element = () => { |
| 113 | + if (!useScriptElementForInitialPage) { |
| 114 | + return createElement( |
| 115 | + 'div', |
| 116 | + { |
| 117 | + id, |
| 118 | + 'data-page': JSON.stringify(initialPage), |
| 119 | + }, |
| 120 | + reactApp as ReactElement, |
| 121 | + ) |
| 122 | + } |
| 123 | + |
| 124 | + return createElement( |
| 125 | + Fragment, |
| 126 | + null, |
| 127 | + createElement('script', { |
| 128 | + 'data-page': id, |
| 129 | + type: 'application/json', |
| 130 | + dangerouslySetInnerHTML: { __html: JSON.stringify(initialPage) }, |
| 131 | + }), |
| 132 | + createElement('div', { id }, reactApp as ReactElement), |
| 133 | + ) |
| 134 | + } |
| 135 | + |
| 136 | + const body = await render(element()) |
117 | 137 |
|
118 | 138 | return { head, body } |
119 | 139 | } |
|
0 commit comments