首页 > 解决方案 > gatsby ssr - 在其他插件之前将脚本添加到标题

问题描述

我正在使用 Gatsby,需要在其他插件之前在标题中添加一个脚本。

如果我通过添加它gatsby-ssr.js

exports.onRenderBody = ({ setHeadComponents }) => setHeadComponents([#MY-SCRIPT#]);

它是最后添加的。

如何在其他插件之前添加它?

标签: reactjsgatsby

解决方案


除了onRenderBody,用于onPreRenderHTML重新排序您的脚本。

exports.onRenderBody = ({ setHeadComponents }) =>
  setHeadComponents([
    <script key='myscript' src='...' />
  ]);

exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => {
  const headComponents = getHeadComponents()

  // reorder your array with the sort method, by putting your item at top
  const orderedComponents = headComponents.sort((item) => (item.key === 'your-key' ? -1 : 1));  const orderedComponents = reorder(headComponents)
  replaceHeadComponents(orderedComponents)
}

有关详细信息,请参阅 SSR API 上的 Gatsby 文档


推荐阅读