由于HTML导入现在已在Chrome中弃用( www.chromestatus/feature/5144752345317376 )并将其删除,我想知道还有哪些替代方法.
Since Html-Imports are now deprecated in Chrome (www.chromestatus/feature/5144752345317376) and will be removed, I wonder what the alternatives are.
我目前正在使用HTML导入来导入HTML模板.到目前为止,我只看到两种选择:
I'm currently using Html-Imports to import Html-Templates. I see only two alternatives so far:
- 将所有HTML文件捆绑在一个文件中.这还将缩短生产中的下载时间,但是这将减少封装和模块化.有一个聚合物捆绑程序可以通过遍历单独的HTML文件中的HTML导入语句来完成此工作.但这意味着,即使将来任何浏览器都不支持HTML导入,也保留在我的代码中.
- 使用XHttpRequests构建某种模块加载器,并在运行时将模板编织到一个HTML文件中.这样可以保留封装和模块化,但是对我来说很难闻,因为我基本上可以自行重建import-Statements.
是否存在一种导入Html模板的新方法? (通过香草",我基本上是指不涉及任何其他工具(如预编译器或打包器)的方法)
Is there a new vanilla way to import Html-Templates? (By "vanilla" I basically mean a way without any additional tools like precompiler or bundler involved)
推荐答案HTML导入的弃用实质上改变了资源的加载顺序.自定义元素本质上已成为脚本优先而不是模板优先.如果您的元素需要模板,请从脚本中加载它.如果没有,那就去上班.坦白说,虽然我在最初的几周内一直抵制它,但我已经变得很喜欢它.事实证明,加载诸如模板之类的外部资源还不错.
The deprecation of HTML Imports has essentially changed the load order of resources. Custom Elements have essentially become script-first rather than Template-first. If your element needs a template, load it from the script. If not, just go to work. Frankly, while I was resistant to it for the first couple of weeks, I have grown to love it. And it turns out that loading external resources such as templates is not so bad.
以下是一些简单的代码,它们将从外部文件加载HTML模板:
Here is some simple code that will load an HTML Template from an external file:
使用异步/等待:
async function getTemplate(filepath) { let response = await fetch(filepath); let txt = response.text(); let html = new DOMParser().parseFromString(txt, 'text/html'); return html.querySelector('head > template'); }基于承诺:
function getTemplate(filepath) { return fetch(filepath) .then(response => { let txt = response.text(); let html = new DOMParser().parseFromString(txt, 'text/html'); return html.querySelector('template'); }); }两者都可以通过以下两种方式调用:
Both can be invoked with both of the following:
异步/等待:
let tpl = await getTemplate('path/to/template.html');承诺:
getTemplate('path/to/template.html') .then(function doSomething(tpl) { // Put your code here... });生成的代码非常简单,可以很轻松地以多种方式实现.实际上,我有一个为我处理的超类,我的所有自定义元素都继承自它.您可以改用mixin,这也是我过去也做过的事情.
The resulting code is simple enough that it can be implemented with very little effort in a variety of ways. In fact, I have a little SuperClass that handles it for me and all of my custom-elements inherit from it. You could use a mixin, instead, which I have also done in the past.
艰苦的工作只是翻转订单,即使您不使用数千个组件,也不是很难.只需很少的工作就可以实现自动化.
The hard work is just flip-flopping the order, and even that is not very hard unless you are using 1000s of components. It could probably be automated with very little work.
更多推荐
如何在没有HTML导入的情况下打包或导入HTML模板
发布评论