在页面加载后加载Google Adsense,可以通过以下步骤实现:
<script>
标签来引入Google Adsense的广告代码。Renderer2
服务来动态创建并添加<script>
标签到DOM中。首先,在组件的构造函数中注入Renderer2
服务:import { Component, OnInit, Renderer2 } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
constructor(private renderer: Renderer2) { }
ngOnInit() {
this.loadGoogleAdsense();
}
loadGoogleAdsense() {
const script = this.renderer.createElement('script');
script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
script.async = true;
script.defer = true;
this.renderer.appendChild(document.body, script);
}
}
<div id="google-adsense-container">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="YOUR_AD_CLIENT"
data-ad-slot="YOUR_AD_SLOT"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
</div>
请注意,将YOUR_AD_CLIENT
和YOUR_AD_SLOT
替换为你在Google Adsense上获得的广告客户端ID和广告槽ID。
ngAfterViewInit()
生命周期钩子函数来初始化Google Adsense广告。在这个钩子函数中,可以使用window.adsbygoogle.push()
方法来加载广告。例如:import { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements AfterViewInit {
ngAfterViewInit() {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
}
这样,当页面加载完成后,Google Adsense广告将会被加载并显示在指定的容器中。
推荐的腾讯云相关产品:腾讯广告(https://cloud.tencent.com/product/tga)
领取专属 10元无门槛券
手把手带您无忧上云