优化adsense加载

This commit is contained in:
tangly1024
2023-06-20 20:52:23 +08:00
parent 7f9f522889
commit 550c798a46

View File

@@ -4,28 +4,31 @@ import { useEffect } from 'react'
export default function GoogleAdsense() { export default function GoogleAdsense() {
const initGoogleAdsense = () => { const initGoogleAdsense = () => {
const ads = document.getElementsByClassName('adsbygoogle').length setTimeout(() => {
const newAdsCount = ads const ads = document.getElementsByClassName('adsbygoogle')
if (newAdsCount > 0) { const adsbygoogle = window.adsbygoogle
for (let i = 0; i <= newAdsCount; i++) { if (ads.length > 0) {
try { for (let i = 0; i <= ads.length; i++) {
// eslint-disable-next-line no-undef try {
(adsbygoogle = window.adsbygoogle || []).push({}) adsbygoogle.push(ads[i])
} catch (e) { console.log('adsbygoogle', i, ads[i], adsbygoogle)
} catch (e) {
}
} }
} }
} }, 100)
} }
const router = useRouter() const router = useRouter()
useEffect(() => { useEffect(() => {
initGoogleAdsense()
router.events.on('routeChangeComplete', initGoogleAdsense) router.events.on('routeChangeComplete', initGoogleAdsense)
return () => { return () => {
router.events.off('routeChangeComplete', initGoogleAdsense) router.events.off('routeChangeComplete', initGoogleAdsense)
} }
}, [router.events]) }, [router])
return null return null
} }
@@ -33,6 +36,7 @@ export default function GoogleAdsense() {
* 文章内嵌广告单元 * 文章内嵌广告单元
* 请在GoogleAdsense后台配置创建对应广告并且获取相应代码 * 请在GoogleAdsense后台配置创建对应广告并且获取相应代码
* 修改下面广告单元中的 data-ad-slot data-ad-format data-ad-layout-key(如果有) * 修改下面广告单元中的 data-ad-slot data-ad-format data-ad-layout-key(如果有)
* 添加 可以在本地调试
*/ */
const AdSlot = ({ type = 'show' }) => { const AdSlot = ({ type = 'show' }) => {
if (!BLOG.ADSENSE_GOOGLE_ID) { if (!BLOG.ADSENSE_GOOGLE_ID) {