Skip to content

Instantly share code, notes, and snippets.

@kj-sh604
Created August 5, 2024 04:16
Show Gist options
  • Save kj-sh604/a2203be45f25c277e12e41e3a2c28d1a to your computer and use it in GitHub Desktop.
Save kj-sh604/a2203be45f25c277e12e41e3a2c28d1a to your computer and use it in GitHub Desktop.
Creates an <include-html> tag for HTML partials. Works similarly to "include" and "require" in PHP.
// Example Usage in HTML:
// <include-html file="partials/fancy.html"></include-html>
class HTMLIncludeElement extends HTMLElement {
connectedCallback() {
const filepath = this.getAttribute('file');
if (filepath) {
fetch(filepath)
.then(response => {
if (!response.ok) {
throw new Error(`network response was not ok for ${filepath}`);
}
return response.text();
})
.then(data => {
this.innerHTML = data;
})
.catch(error => {
console.error('error loading the html: ', error);
this.innerHTML =
'<br /><pre>failed to load content. <br /><br />failsafe: <br />' +
'<br /><a href="javascript:history.back()">< go back</a><br />' +
'<br /><a href="/">^ go to homepage</a></pre>';
});
}
}
}
customElements.define('include-html', HTMLIncludeElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment