You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Gatsby站点的<html>标签添加AMP必填属性以识别为AMP网站

Hey there! Let's tackle your question about adding required AMP attributes to the <html> tag—first for Gatsby, then for general HTML setups.

In Gatsby: Add AMP Attributes to the <html> Tag

Gatsby lets you modify the root HTML structure via its server-side rendering (SSR) API. Here's how to do it:

  • First, create or edit the gatsby-ssr.js file in your project's root directory (this file controls how Gatsby renders HTML on the server).
  • Export the onRenderBody function, which gives you access to the setHtmlAttributes method. Use this to add the required amp attribute (and any other attributes like lang you need).

Here's a working code example:

exports.onRenderBody = ({ setHtmlAttributes }) => {
  setHtmlAttributes({
    amp: true,
    lang: "en" // Optional but recommended for accessibility
  });
};

When you build or run your Gatsby site, this will generate an <html> tag like <html amp lang="en">—which meets AMP's mandatory requirement.

If you're using the official gatsby-plugin-amp, double-check its configuration, but manually setting attributes via onRenderBody gives you direct control over the final output.

General HTML Scenario: Add AMP Attributes

For static HTML sites or non-Gatsby frameworks, it's straightforward—just edit your root HTML file directly:

  • Add the amp attribute (or the equivalent ⚡ lightning symbol) directly to the <html> tag:
<html amp lang="en">
<!-- OR -->
<html ⚡ lang="en">
  • Remember, AMP requires more than just this attribute. You'll also need to include the AMP core script in your <head> section:
<script async src="https://cdn.ampproject.org/v0.js"></script>

And make sure all other elements on the page follow AMP's rules (like using <amp-img> instead of standard <img> tags, avoiding custom JavaScript, etc.).

内容的提问来源于stack exchange,提问作者nyedidikeke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:42:30