HTML Import API废弃后如何将项目内HTML文件直接导入现有HTML文档
原生JS实现HTML导入的可行方案
以下方案均基于纯原生API实现,不需要引入任何第三方依赖。
方案1:Fetch API封装通用加载函数
是兼容性最好、灵活度最高的方案,几行代码就能替代原来的HTML Import功能:
/** * 加载外部HTML文件并插入到指定容器 * @param {string} url 外部HTML文件路径 * @param {string} targetSelector 目标容器选择器,默认插入到body * @param {string} position 插入位置,同insertAdjacentHTML的位置参数 */ async function loadHTML(url, targetSelector = 'body', position = 'beforeend') { const res = await fetch(url); if (!res.ok) throw new Error(`HTML加载失败:${res.status}`); const htmlContent = await res.text(); const target = document.querySelector(targetSelector); target.insertAdjacentHTML(position, htmlContent); // 可选:执行引入HTML中的script标签(默认插入的HTML内script不会执行) target.querySelectorAll('script').forEach(oldScript => { const newScript = document.createElement('script'); [...oldScript.attributes].forEach(attr => newScript.setAttribute(attr.name, attr.value)); newScript.textContent = oldScript.textContent; oldScript.replaceWith(newScript); }); } // 调用示例 loadHTML('./components/header.html', '#header-container');
本地开发时直接打开HTML文件会触发跨域限制,使用任意本地静态服务(如VS Code的Live Server插件)运行即可正常使用。
方案2:ES模块导入断言
现代浏览器已经原生支持通过导入断言直接引入HTML文件,不需要手动发请求:
// 直接导入得到HTML Document对象 import headerHtml from './components/header.html' assert { type: 'html' }; // 插入到页面 document.querySelector('#header-container').append(...headerHtml.body.children);
该特性支持Chrome 91+、Edge 91+、Firefox 118+版本,不需要兼容旧浏览器的项目可以直接用。
方案3:自定义导入标签(Web Components方案)
适合需要在HTML代码中直接声明引入的场景,封装后不需要写JS调用代码:
// 注册自定义元素 class ImportHtml extends HTMLElement { async connectedCallback() { const src = this.getAttribute('src'); if (!src) return; const res = await fetch(src); this.innerHTML = await res.text(); } } customElements.define('import-html', ImportHtml);
使用时直接在HTML中写标签即可:
<import-html src="./components/header.html"></import-html> <import-html src="./components/footer.html"></import-html>
方案选型参考
- 需要兼容旧浏览器、要灵活控制加载逻辑:选方案1
- 不需要兼容老版本浏览器、项目已基于ES模块开发:选方案2
- 需要批量模板化引入、使用Web Components技术栈:选方案3
内容的提问来源于stack exchange,提问作者J. B
相关产品推荐
相关产品推荐

