在現代網站中,廣告不只是收益來源,也會直接影響使用者體驗。 Hilltop Ads 提供的是「直接插入 script」的整合方式, 但在 React / Next.js 專案中,若照官方範例直接貼 script, 往往會造成 hydration 問題、重複載入,甚至出現奇怪的錯誤訊息。
本篇將示範如何正確地將 Hilltop 廣告元件化, 讓它在 Next.js(App Router / Client Component)中穩定運作, 同時避免版面跑版與 scrollbar 問題。
Hilltop 官方提供的 script 寫法,本質上是:
document.scripts 與插入順序performance.mark()在 Next.js 中若直接貼上,常見問題包含:
Performance mark does not exist 錯誤核心原則只有三個:
'use client')'use client'
import { Box } from '@mui/material'
interface HilltopAdsProps {
width?: number
height?: number
}
const HilltopAdsComponent = ({ width = 300, height = 250 }: HilltopAdsProps) => {
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<script>
(function(jeu){
var d = document,
s = d.createElement('script'),
l = d.scripts[d.scripts.length - 1];
s.settings = jeu || {};
s.src = "XXX";
s.async = true;
s.referrerPolicy = 'no-referrer-when-downgrade';
l.parentNode.insertBefore(s, l);
})({});
</script>
</body>
</html>
`;
return (
<Box
sx={{
width,
height,
overflow: 'hidden',
marginY: '12px',
}}
>
<iframe
srcDoc={html}
width={width}
height={height}
sandbox="allow-scripts allow-same-origin"
style={{
border: 'none',
display: 'block',
}}
/>
</Box>
)
}
export default HilltopAdsComponent
在任何 client component 中直接使用即可:
<HilltopAdsComponent width={300} height={250} />
overflow: hidden 防止 1px 誤差display: block 避免 inline iframe 造成基線空隙在 React / Next.js 中整合第三方廣告, 關鍵不是「能不能顯示」,而是能不能穩定顯示。 透過 client component + iframe 隔離, 可以有效避免 hydration、效能標記錯誤與版面跑版問題, 這也是目前整合 Hilltop Ads 最安全的方式。





