I’m developing SSR application, and have a problem. <script>
tag added programaticaly is exisits only in a server response, but it is not instert into the DOM. The script appears in DOM only after page reload or on initial load. But it is not in the DOM if user navigates to the page interacting with UI.
This is a service using in Page constructor.
@Injectable({
providedIn: 'root',
})
export class ScriptService {
private readonly platform = inject(PLATFORM_ID)
private readonly document = inject(DOCUMENT)
private readonly head = this.document.head
public addScript(src: string): void {
if (!this.isServer()) {
return
}
const script = this.document.createElement('script')
script.setAttribute('src', src)
this.head.appendChild(script)
}
private isServer(): boolean {
return isPlatformServer(this.platform)
}
}
export class ExampleComponent {
private readonly scriptService = inject(ScriptService)
constructor() {
this.scriptService.addScript('qweqwe')
}
}
If I delete the section that checks, is the action happens on the server, everything works fine. But I don’t understand why should delete it? Why should I insert the script on the client side if I can add it to the DOM on the server side?
Thank you!