Script was added to the head , but when I deploy it after build, it was added twice and an error occurred

154 Views Asked by At

I am currently making and operating the web using the angular 11 version. For page data analysis, I had to add marketing-related scripts to the head. When I searched it, I found out that I could add scripts to components using rederer2 and Inject, and I added them to the ngOninit part as below

import { Component, OnInit, Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-teamroom-apply',
  templateUrl: './teamroom-apply.component.html',
  styleUrls: ['./teamroom-apply.component.css']
})
export class TeamroomApplyComponent implements OnInit {

  constructor(
    private renderer2: Renderer2,
    @Inject(DOCUMENT) private _document 
  ) {
    const r = this.renderer2.createElement('script');
    r.type = 'text/javascript';  
    r.src = '//wcs.naver.net/wcslog.js'  
    this.renderer2.appendChild(this._document.head, r);
   }

  ngOnInit(): void {

    const s = this.renderer2.createElement('script');
    s.type = 'text/javascript';      
    s.text = `
      var _nasa={};
      if(window.wcs) _nasa["cnv"] = wcs.cnv("5","1"); 
    `;
   this.renderer2.appendChild(this._document.head, s);

  }

}

And after building, I deployed it, but it was inserted into the head twice, so I keep getting errors

enter image description here

Can I know how to fix it?

I think, when build, something is done twice. But I don't know for sure

2

There are 2 best solutions below

1
Andrew Allen On

Check if the script exists before adding which can be done with document.head.querySelector

Stackblitz

main.ts

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';

// See index.html for existing script tag

@Component({
  selector: 'my-app',
  standalone: true,
  template: `
    <p>See \`index.html\` for existing script tag</p>
  `,
})
export class App {
  ngOnInit() {
    const scriptSrc = 'yadayada';
    const script = document.head.querySelector(`script[src="${scriptSrc}"]`);

    if (!!script) {
      console.log('Script already exists!');
    } else {
      console.log('Script does not exist');
    }
  }
}

bootstrapApplication(App);

index.html

<html>
  <head>
    <title>My app</title>

    <!-- comment out this script to see this works -->
    <script type="text/javascript" src="yadayada">
      console.log("Hello from script")
    </script>
    <!-- -->
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
1
MGX On

You probably display your component twice, resulting on the script being added twice.

But anyway, the best option for this kind of script is to write it in a separate JS file, and to add a reference to this JS file into the scripts part of your angular(-cli).json file.