Since Html-Imports are now deprecated in Chrome (https://www.chromestatus.com/feature/5144752345317376) and will be removed, I wonder what the alternatives are.
I'm currently using Html-Imports to import Html-Templates. I see only two alternatives so far:
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)
Feature: HTML Imports (Removed) The spec is superseded by ES modules, which is widely supported.
Paste in HTML code. If you have code copied, click Paste in code → Add your Template name → paste the Template HTML you have copied → click Import. You can access your custom HTML template on the Saved templates page and as a saved template in your campaigns and automation.
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.
Here is some simple code that will load an HTML Template from an external file:
using async/await:
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');
}
Promise-based:
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:
async/await:
let tpl = await getTemplate('path/to/template.html');
Promises:
getTemplate('path/to/template.html')
.then(function doSomething(tpl) {
// Put your code here...
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With