Skip to content

Instantly share code, notes, and snippets.

@A35G
Last active December 4, 2024 16:01
Show Gist options
  • Select an option

  • Save A35G/21a22673d2ccb6edf37b008957a3c48d to your computer and use it in GitHub Desktop.

Select an option

Save A35G/21a22673d2ccb6edf37b008957a3c48d to your computer and use it in GitHub Desktop.
jQuery's .load() in pure JavaScript - Version using fetch
/**
* Loads an HTML document from a URL (or a portion of it via the “selector” parameter) within a “target” element.
* If present, executes upon completion, a callback.
*
* Example usage:
* loadContent('#target', 'https://www.mypage.tld');
* loadContent('#target', 'https://www.mypage.tld', '#selector');
* loadContent('#target', 'https://www.mypage.tld', '#selector', () => console.log('Hi!'));
* loadContent('#target', 'https://www.mypage.tld', '#selector', myCallback);
* loadContent('#target', 'https://www.mypage.tld', '', myCallback);
*
* @method loadContent
* @param {string} target
* @param {string} url
* @param {string} selector
* @param {function} callback
*/
const checkURL = url => {
try {
return Boolean(new URL(url));
} catch(e) {
return false;
}
}
const isEmpty = (args) => (args === "" || args === 0 || args === "0" || args === null || args === !1 || args === undefined || args.length === 0);
const loadContent = async function(target, url, selector, callback) {
if (typeof target === 'string' && !isEmpty(target)) {
if (typeof url === 'string' && !isEmpty(url)) {
if (checkURL(url)) {
if (document.querySelectorAll(target).length > 0) {
const trg = document.querySelector(target);
trg.innerHTML = '';
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const dt = await response.text();
if (typeof selector === 'string' && !isEmpty(selector)) {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(dt, "text/html");
if (htmlDoc.querySelectorAll(selector).length > 0) {
const section = htmlDoc.querySelector(selector);
trg.appendChild(section);
} else {
throw new Error('Invalid selector: ', selector);
}
} else {
trg.innerHTML = dt;
}
if (typeof callback !== 'undefined' && typeof callback !== null) {
if (typeof callback === 'function') {
callback();
} else {
throw new Error('Invalid callback: ', callback);
}
}
} catch (error) {
console.error(error.message);
}
} else {
throw new Error('Invalid target: ', target);
}
} else {
throw new Error('Invalid URL: ', url);
}
} else {
throw new Error('Invalid URL: ', url);
}
} else {
throw new Error('Invalid target: ', target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment