对 NextJS 来说非常陌生,我在尝试在我的路线页面之一上显示第三方 eBay 脚本时遇到了问题。它似乎只在我重新加载时有时显示。当页面通过链接/路由切换到商店页面时,不显示任何内容。
知道我可能做错了什么或可以使用其他方法来解决这个问题吗?谢谢!
import Script from "next/script";
import Image from "next/image";
const page = () => {
return (
<>
<section className="max-container padding-container flex flex-col gap-20 py-10 md:gap-28 lg:py-20 xl:flex-row">
{/*rest of code here*/}
</section>
<div className="2xl:max-container relative flex flex-col lg:mb-10 lg:py-10 bg-white">
<Script
type="text/javascript"
src="https://www.auctionnudge.app/feed/item/js/theme/responsive/page/init/img_size/120/cats_output/dropdown/search_
box/1/blank/1/show_logo/1/lang/english/SellerID/example/siteid/0/MaxEntries/35/sortOrder/StartTimeNewest/target/52d212f5f"
/>
<div id="auction-nudge-52d212f5f" />
</div>
</>
);
};
export default page;
我看到其他用户问过,我尝试使用strategy =“beforeInteractive”和其他方法,例如useEffect,但没有运气。我需要只在这个特定页面上加载脚本,所以我认为我不能将它放在layout.tsx中。
看来您只能在
beforeInteractive
组件中加载 Document
脚本(服务器端加载,注入到发送到浏览器的 HTML 中)。
将其加载到任意页面中无法与
beforeInteractive
一起使用。
例如,
/pages/_document.js
:
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<Script
src="https://example.com/script.js"
strategy="beforeInteractive"
/>
</body>
</Html>
)
}
此示例直接取自此处的 NextJS 文档:https://nextjs.org/docs/pages/api-reference/components/script#beforeinteractive
如果您想要的话,可以使用其他策略来加载脚本客户端。当然,您只能期望脚本在加载后之后才能工作。