Created
August 5, 2024 04:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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