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

如何将_head.html文件内容插入index.html的<head>标签中?

正确实现方式

<link rel="import">是已经被废弃的HTML特性,现代浏览器都不再支持,所以你用的方法无效。下面给你几种可行的解决办法:

1. 用前端构建工具(推荐方案)

Webpack、Vite、Parcel这类工具都能帮你拆分和合并HTML文件,拿Vite举例:

  • 先安装Vite和vite-plugin-html插件,然后在vite.config.js里配置:
import { createHtmlPlugin } from 'vite-plugin-html'
import fs from 'fs'

export default {
  plugins: [
    createHtmlPlugin({
      inject: {
        data: {
          headContent: fs.readFileSync('./_head.html', 'utf-8')
        }
      }
    })
  ]
}

接着在index.html的head标签里写:

<head>
  <%= headContent %>
</head>

运行构建命令后,工具会自动把_head.html的内容合并到index.html里。

2. 服务器端包含(SSI)

如果你的服务器支持SSI(比如Apache、Nginx),直接用服务器的指令导入:

  • Apache环境:在index.html的head里添加
<head>
  <!--#include virtual="_head.html" -->
</head>

要记得开启Apache的SSI模块,要么把文件后缀改成.shtml,要么配置让Apache解析.html文件的SSI指令。

  • Nginx环境:先在配置里开启ssi on;,然后在index.html里写
<head>
  <!--#include file="_head.html" -->
</head>

3. JavaScript动态加载(应急方案)

不想折腾构建工具或服务器的话,用JS动态读取文件内容插入:
在index.html的head末尾加这段代码:

<head>
  <script>
    fetch('_head.html')
      .then(res => res.text())
      .then(content => {
        document.head.insertAdjacentHTML('afterbegin', content);
      });
  </script>
</head>

注意:这种方法可能导致meta标签加载延迟,影响浏览器解析,只适合简单场景。

4. 静态站点生成器

如果用Jekyll、Hexo这类工具,直接用它们的include语法就行:
比如Jekyll里,index.html的head这么写:

<head>
  {% include _head.html %}
</head>

生成站点的时候会自动把内容合并进去。

内容的提问来源于stack exchange,提问作者Mr. Brooks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:22:45