如何在Next.js应用程序中动态地将代码插入到head中?

yyhrrdl8  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(305)

我想向Google展示分页实现中页面之间的关系。因此,我想在head中添加以下代码块:

<link rel="prev" href="https://www.example.com/article?story=abc&page=1" />
<link rel="next" href="https://www.example.com/article?story=abc&page=3" />

当我把它添加到一个变量或者用一个函数使它动态化时,它在我的Next.js应用程序中的head中没有显示。
例如:

const pageRelationships = `<link rel="prev" href="https://www.example.com/article?story=abc&page=1" /><link rel="next" href="https://www.example.com/article?story=abc&page=3" />`

head中实现:

<Head>
{pageRelationships}
</Head>

您对如何在head中插入代码块有什么建议吗?

wlwcrazw

wlwcrazw1#

您可以使用以下代码:

// Make sure that we are on the client side
if(typeof document !== 'undefined') {
  const firstLinkElement = docment.createElement("link");
  firstLinkElement.rel = "prev";
  firstLinkElement.href = "https://www.example.com/article?story=abc&page=1";
  document.head.appendChild(firstLinkElement);
  const secondLinkElement = docment.createElement("link");
  secondLinkElement.rel = "next";
  secondLinkElement.href = "https://www.example.com/article?story=abc&page=3";
  document.head.appendChild(secondLinkElement);
}

或者这个:

// Make sure that we are on the client side
if(typeof document !== 'undefined') {
  const pageRelationships = `<link rel="prev" href="https://www.example.com/article?story=abc&page=1" /><link rel="next" href="https://www.example.com/article?story=abc&page=3" />`;
  document.head.innerHTML = document.head.innerHTML + pageRelationships;
}

相关问题