有没有办法将 HTML 从我的项目文件直接导入到我的工作 HTML 文档中?

Is there a way to import HTML from my project files directly into my working HTML document?

一旦 HTMl 导入 API 被弃用,我们都失去了一种轻松直接地将文件中的 HTML 代码带入我的原始 JS 工作文档的方法,以及许多答案这个问题要么已经过时,要么没有帮助,要么太难了(看着你,AJAX)。自从引入 ES 模块以来,许多人认为在这些部分会有一些协作,但它仍然相对未受影响。对于前端 HTML 导入,我们现在要做什么?

这个问题的现代、干净的解决方案是利用一些东西:

  1. ES6+ javascript fetch API
  2. ES8+ async/await 函数
  3. ES6+ 匿名 Javascript 函数

例如,

假设我想将我的导航栏导入我的每个网页。通常,post-html-imports 的解决方案实际上是在每个页面中嵌入相同的导航栏。

文件Navbar.html

<div class="navbar">
  <a href="#page1">Location 1</a>
  <a href="#page2">Location 2</a>
  <a href="#page3">Location 3</a>
  <!-- and so on... -->
</div>

这是一段冗长、烦人且重复的代码,需要继续编写。但是,我们可以使用多种方法的组合将它嵌入到每个 HTML 页面的同一位置。

文件Fetch.js

//Assuming that the code is in another file
async function fetchHTML(path = '/navbar.html'){
 let fetchResponse = await fetch(path); //fetch data from file at path
 let htmlString = await fetchResponse.text(); //get all text from file
 return htmlString; //return the HTML string. Is compatible with DOMParser.parseFromString()
}

正如您在上面看到的,async/await 组合是使用 fetch() 最有用的技巧之一。请注意,此文件必须托管在您的项目文件中,否则您将收到 CORS 错误。

要实际实现它,请使用以下代码。

importNavbar.js

(async function(path=''){
 let element = document.body; //this can be *any* DOM element, just select it first
 element.insertAdjacentHTML('afterbegin', await fetchHTML(path)); //This is a native method, has a nice tutorial on w3schools.
})()

只需将以下 HTML 添加到您的主 HTML 文件中,您就应该一切就绪!

index.html

<!-- at the end of your body element... -->
<script src="Fetch.js"></script>
<script src="importNavbar.js"></script>
<script src="YOUR ADDITIONAL FILES.js"></script>

现在,如果您需要加载相对较大的代码段,此方法很棒。但是,这不是最快的方法。工作得更快(因此更支持其他设备)的是将我们的匿名函数作为一个适当的函数进行小的重写。

importNavbar.js,重写

function injectHTML(location='',HTMLstr=''){
 let element = document.body; //Identical to our original
 element.insertAdjacentHTML(location, HTMLstr);
}
injectHTML(`
template string containing your exact html
`);

虽然这个解决方案不是那么稳健,但它更快,对于小字符串来说更合理。

希望我回答了一些问题!

兼容性图表(无 IE):

code bit chrome edge firefox safari opera
element.insertAdjacentHTML 1 4 8 4 7
fetch() 42 14 40 10.1 29
async/await 55 15 52 11 42
template literals ES6 ES6 ES6 ES6 ES6
anonymous functions ES6 ES6 ES6 ES6 ES6

如果有人要添加任何内容/优化,请随时发表评论。