能否在HTML文档HEAD部分引入外部HTML文件?实测遇加载异常
能否在HTML的HEAD部分引入其他文件内容?
网上有不少关于HTML文件间内容引入的示例,我想确认:能不能在调用方HTML文档的HEAD部分引入其他文件的内容?
我的尝试
源文件
<html> <head> <div id="headerInclude"></div> <script src="/lforms-examples/lib/jquery-1.11.3/jquery.min.js"></script> <script>$("#headerInclude").load("/lforms-examples/pages/header-footer/ComponentHeader.html");</script> </head> <body> <h1>Basic Questionnaire Example Using Header</h1> </body> </html>
被引入文件
<html> <head> <link rel="shortcut icon" type="image/x-icon" href="/lforms-examples/img/nachc-favico.png"> </head> </html>
结果
引入的link标签被浏览器移到了body区域,导致favicon.ico无法被正确识别。
问题原因及解决办法
问题根源
<div>不能放在<head>里:HTML规范明确要求,<head>内只能放元数据类标签(比如<link>、<script>、<title>),<div>属于页面内容元素,浏览器会自动把它移到<body>中,你通过load插入的内容自然也跟着到了body里。- 被引入文件结构冗余:你加载的是一个完整的HTML文件,jQuery的
load方法处理这类文件时,会自动忽略外层的<html>和<head>标签,再加上容器被移到body,最终link标签就出现在了错误的位置。
可行解决方案
方案1:精简被引入文件+直接插入head
先把被引入的ComponentHeader.html改成只保留需要的内容:
<link rel="shortcut icon" type="image/x-icon" href="/lforms-examples/img/nachc-favico.png">
然后修改源文件,直接用jQuery把内容插入到head中,不需要额外的div容器:
<html> <head> <script src="/lforms-examples/lib/jquery-1.11.3/jquery.min.js"></script> <script> $.get("/lforms-examples/pages/header-footer/ComponentHeader.html", function(data) { $("head").append(data); }); </script> </head> <body> <h1>Basic Questionnaire Example Using Header</h1> </body> </html>
方案2:原生JavaScript实现(无需jQuery)
如果不想依赖jQuery,用原生JS也能实现:
<html> <head> <script> fetch("/lforms-examples/pages/header-footer/ComponentHeader.html") .then(response => response.text()) .then(data => { document.head.insertAdjacentHTML('beforeend', data); }); </script> </head> <body> <h1>Basic Questionnaire Example Using Header</h1> </body> </html>
同样需要先精简被引入文件的内容。
方案3:服务器端包含(SSI)
如果你的服务器支持SSI(比如Apache、Nginx),可以用服务器端的方式引入,内容会在页面发送给浏览器前就插入到正确位置,完全不会有DOM移动的问题。
在源文件的head里添加:
<!--#include virtual="/lforms-examples/pages/header-footer/ComponentHeader.html" -->
被引入文件同样只需要保留link标签即可。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

