You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10:非生产环境下app.component.html加载JS脚本失败问题

问题根源:Angular模板会自动忽略<script>标签

嘿,这个问题其实是Angular的模板安全机制在起作用!Angular为了避免潜在的XSS风险和优化模板渲染,会直接忽略模板文件(比如你的app.component.html)里的所有<script>标签——不管你给它加了*ngIf还是其他结构指令,它都不会被编译渲染到最终的浏览器DOM中。这就是为什么<p>标签能正常显示(因为它是普通元素,Angular会处理),但<script>完全没加载的原因。

两种可行的解决方案

方案1:在组件类中动态加载脚本

你可以在组件的TypeScript代码里,根据环境变量判断,手动创建<script>标签并插入到DOM中,这样Angular就不会拦截它了。示例代码如下:

import { Component, OnInit } from '@angular/core';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    // 仅在开发环境加载脚本(这里假设environment.production为true时是生产环境)
    if (!environment.production) {
      this.loadExternalScript('https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js');
      this.loadExternalScript('src/assets/js/my.js');
    }
  }

  private loadExternalScript(src: string): void {
    const scriptElement = document.createElement('script');
    scriptElement.src = src;
    scriptElement.type = 'text/javascript';
    document.body.appendChild(scriptElement);
  }
}

方案2:通过angular.json配置环境专属脚本

如果这些脚本是全局依赖,更推荐用Angular的环境配置来处理,这样构建时会自动注入,不需要在组件里写额外逻辑:

  1. 打开项目根目录的angular.json文件
  2. 找到architect > build > configurations > development节点(对应开发环境的构建配置)
  3. 在scripts数组中添加你的脚本路径:
"configurations": {
  "development": {
    // 其他已有配置...
    "scripts": [
      "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js",
      "src/assets/js/my.js"
    ]
  },
  "production": {
    // 生产环境不添加这些脚本,保持原有配置即可
    // 其他已有配置...
  }
}

这样当你用ng serve启动项目(默认是开发环境)时,这些脚本会自动被注入到index.html的末尾;生产构建(ng build --prod)时则不会包含它们,完美匹配你的需求。

内容的提问来源于stack exchange,提问作者Roman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:03:02