Skip to content

Instantly share code, notes, and snippets.

@lazamar
Last active April 12, 2022 21:53
Show Gist options
  • Save lazamar/f213d94d08a8212bb0a59a4ec2fbc964 to your computer and use it in GitHub Desktop.
Save lazamar/f213d94d08a8212bb0a59a4ec2fbc964 to your computer and use it in GitHub Desktop.
Vanilla JS implementation of JQuery's .load
/**
* Loads an HTML document from a URL and retuns an element selected using
* the 'selector' parameter
* Example usage:
* loadPageSection('./myPage.html', '#container', (r, err) => console.log(r, err));
*
* @method loadPageSection
* @param {String} url
* @param {String} selector - A valid CSS selector
* @param {Function} callback - To be called with two parameters (response, error)
* @return {void} - The Element collected from the loaded page.
*/
window.loadPageSection = function loadPageSection(url, selector, callback) {
if (typeof url !== 'string') {
throw new Error('Invalid URL: ', url);
} else if (typeof selector !== 'string') {
throw new Error('Invalid selector selector: ', selector);
} else if (typeof callback !== 'function') {
throw new Error('Callback provided is not a function: ', callback);
}
var xhr = new XMLHttpRequest();
var finished = false;
xhr.onabort = xhr.onerror = function xhrError() {
finished = true;
callback(null, xhr.statusText);
};
xhr.onreadystatechange = function xhrStateChange() {
if (xhr.readyState === 4 && !finished) {
finished = true;
var section;
try {
section = xhr.responseXML.querySelector(selector);
callback(section);
} catch (e) {
callback(null, e);
}
}
};
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
};
@DriesDD
Copy link

DriesDD commented Aug 14, 2020

The use of the callback function confused me at first, so here is another example.

I used this script to add the same header element (a navigation menu) to different pages, where updating the navigation menu automatically updates the navigation target element in the header of all those pages.

My root folder has the following files:

  • loadpagesection.js, with lazamar's code
  • nav.html, with a <nav id="navsource">Insert navigation menu here.</nav> element.
  • article1.html and all other html files, which all have a <div id="navtarget"></div> element nested in the header. All these pages include:
<script defer>
 (function () {
  loadPageSection("./nav.html", "#navsource", assignToTarget);
  function assignToTarget (source) {document.getElementById('navtarget').appendChild(source)}
  })();
</script>

This way the element with id=navsource is automatically nested under id=navtarget on every page. Note that this does not work in local files, since the same origin policy will prevent you from loading files into other files that are not on the same domain. You will need to host your site online or set up a local server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment