如何在Angular页面的head标签中按域名条件注入Hotjar脚本
Angular 条件动态注入脚本到head的实现方案
推荐使用Angular内置的DOCUMENT注入令牌操作DOM,相比直接调用全局document兼容性更好,也适配服务端渲染等特殊场景。
实现步骤
- 在根组件(通常为
app.component.ts)中注入DOCUMENT对象 - 在
ngOnInit初始化钩子中添加域名判断逻辑 - 域名匹配时执行脚本注入逻辑
完整代码示例
import { Component, OnInit, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit(): void { // 正式域名校验逻辑 const OFFICIAL_ORIGIN = 'https://www.stackoverflow.com'; if (window.origin === OFFICIAL_ORIGIN) { this.injectHotjarScript(); } } private injectHotjarScript(): void { // 避免重复注入 const existScript = this.document.querySelector('script[src*="hotjar"]'); if (existScript) return; // 你提供的hotjar初始化逻辑 (function(h,o,t,j,a,r){ h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)}; h._hjSettings={hjid:*******,hjsv:*}; // 替换为实际的hotjar参数 a=o.getElementsByTagName('head')[0]; r=o.createElement('script');r.async=1; r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv; a.appendChild(r); })(window,this.document,'https://static.hotjar.com/c/hotjar-','.js?sv='); } }
额外说明
- 如果需要脚本更早加载,可以配合
APP_INITIALIZER提供者实现,脚本会在Angular应用启动完成前完成注入 - 不要直接在
index.html的静态脚本中写判断逻辑,会导致服务端渲染、预渲染场景下全局对象访问报错 - 如果需要更换注入的脚本,只需要修改
injectHotjarScript中的脚本创建逻辑即可
内容的提问来源于stack exchange,提问作者Santosh
相关产品推荐
相关产品推荐

