Skip to content

Instantly share code, notes, and snippets.

@greg-raven
Created September 3, 2022 11:59
Show Gist options
  • Save greg-raven/b94dcc37d30cdeeb87ec612708c3dc84 to your computer and use it in GitHub Desktop.
Save greg-raven/b94dcc37d30cdeeb87ec612708c3dc84 to your computer and use it in GitHub Desktop.
Vanilla JavaScript AJAX code for loading external HTML fragments
/*
* Replicates the functionality of jQuery's `load` function,
* used to load some HTML from another file into the current one.
*
* My version of this Stack Overflow answer:
* https://stackoverflow.com/a/38132775/3626537
* And `fetch` documentation:
* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
*
* @param {string} parentElementId - The ID of the DOM element to load into
* @param {string} htmlFilePath - The path of the HTML file to load
*/
function loadHtml(parentElementId, filePath) {
var init = {
method : "GET",
headers : { "Content-Type" : "text/html" },
mode : "cors",
cache : "default"
};
var req = new Request(filePath, init);
fetch(req)
.then(function(response) {
return response.text();
})
.then(function(body) {
// Replace `#` char in case the function
// gets called `querySelector` or jQuery style
if (parentElementId.startsWith("#")) {
parentElementId.replace("#", "");
}
document.getElementById(parentElementId).innerHTML = body;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment