4 ms·
For those following along at home, the reason why you don't need HTML Imports once JS Templates and Modules exist is because HTML Imports are not usable without
by styfle 8y ago
For those following along at home, the reason why you don't need HTML Imports once JS Templates and Modules exist is because HTML Imports are not usable without JS! So you can implement a more elegant solution yourself with a couple lines.
Let's assume you want to use 3 different HTML templates on a page (the html content doesn't matter much for this example).
Here's the example usage of HTML Templates from html5rocks.com:
<script>
function handleLoad(e) {
console.log('Loaded import: ' + e.target.href);
}
function handleError(e) {
console.log('Error loading import: ' + e.target.href);
}
</script>
<link
rel="import"
href="example1.html"
onload="handleLoad(event)"
onerror="handleError(event)"
/>
<link
rel="import"
href="example2.html"
onload="handleLoad(event)"
onerror="handleError(event)"
/>
<link
rel="import"
href="example3.html"
onload="handleLoad(event)"
onerror="handleError(event)"
/>
<script>
function importHtml(selector) {
var content = document.querySelector(selector).import;
var el = content.querySelector('.warning');
document.body.appendChild(el.cloneNode(true));
}
importHtml('link[href="example1.html"]');
importHtml('link[href="example2.html"]');
importHtml('link[href="example3.html"]');
</script>
Now let's compare the same feature with ES6 Modules and Templates using a `helper.js` file.
export async function importHtml(url) {
try {
let res = await fetch(url);
let html = await res.text();
let template = document.createElement('template');
template.innerHTML = html;
let el = template.content.querySelector('.warning');
document.body.appendChild(el.cloneNode(true));
} catch (e) {
console.log(`Error fetching html: ${url}`);
}
}
Then we can import the modules on the page in a very clean way...no HTML Imports spec here.
<script type="module">
import { importHtml } from './helper.js';
importHtml('example1.html');
importHtml('example2.html');
importHtml('example3.html');
</script>
My point is that you don't need HTML imports and you'll have to use JS even with HTML imports so just use JS all the way :)
- irrational 8y agoThat seems like a lot of trouble to replicate the already built-in ability to import external JS and CSS files.