Skip to content

Instantly share code, notes, and snippets.

@Gix075
Created July 5, 2023 09:43
Show Gist options
  • Save Gix075/1ba73d7ba69cdc331935c6847a4489fe to your computer and use it in GitHub Desktop.
Save Gix075/1ba73d7ba69cdc331935c6847a4489fe to your computer and use it in GitHub Desktop.
HTML Partial Includes. A very simple way to include some HTML partials in a page. This script is not tinked for production site but just for html frontend layout creation.
class LoadHtmlpartials {
constructor() {
this.loadPartials();
}
loadPartials() {
document.querySelectorAll('html-partial').forEach(function(htmlPartialWrapper) {
let htmlPartialSrc = htmlPartialWrapper.getAttribute('src'),
thisCallback = htmlPartialWrapper.getAttribute('callback');
fetch(htmlPartialSrc).then(function (response) {
// The API call was successful!
return response.text();
}).then(function (htmlPartial) {
// Convert the HTML string into a document object
/* let parser = new DOMParser();
let partialParsed = parser.parseFromString(partial, 'text/html');
console.log(partialParsed); */
htmlPartialWrapper.innerHTML = htmlPartial;
if(thisCallback != undefined && thisCallback != "" && typeof window[thisCallback] == "function") {
console.log(thisCallback);
window[thisCallback].call()
}
}).catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
});
}
}
new LoadHtmlpartials();
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<html-partial src="./html-partial.html" callback="functionName"></html-partial>
<script src="assets/js/load-html-partials.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment