Dynamically load html
classes/classes.mjs
export class ComponentLoader {
constructor(filePath) {
this.filePath = filePath;
this.componentCache = this.fetchContent(filePath);
}
clearCache() {
this.componentCache = '';
}
async fetchContent(filePath) {
try {
const response = await fetch(filePath);
return await response.text();
} catch (error) {
throw new Error(`Error fetching content: ${error.message}`);
}
}
async injectComponent(selector, target, clearCache = false) {
try {
if (clearCache) {
this.clearCache();
this.componentCache = await this.fetchContent(this.filePath);
}
const targetNode = document.querySelector(target);
if (targetNode) {
const parser = new DOMParser();
const parsedDocument = parser.parseFromString(
await this.componentCache,
'text/html'
);
const clonedNode = parsedDocument
.querySelector(selector)
.cloneNode(true);
targetNode.parentNode.replaceChild(clonedNode, targetNode);
console.log('Component injected successfully.');
} else {
throw new Error(`Target node with selector "${selector}" not found.`);
}
} catch (error) {
console.error('Error injecting component:', error);
throw error;
}
}
}
Class Structure:
-
Constructor: Accepts a filePath parameter which represents the path to the HTML file containing the component to be loaded. It initializes componentCache by fetching the content from the specified file path.
-
clearCache() Method: Clears the componentCache by setting it to an empty string.
-
fetchContent(filePath) Method: Asynchronously fetches the content from the specified file path using the Fetch API. It returns the text content of the fetched file.
-
injectComponent(selector, target, clearCache = false) Method: Asynchronously injects the component into the webpage. It accepts three parameters:
-
selector: A CSS selector representing the element within the loaded component to be injected.
-
target: A CSS selector representing the target element in the webpage where the component will be injected. clearCache (optional, default value is false): A boolean indicating whether to clear the cache before fetching the component again.
How to Use:
app.mjs
- instantiate the ComponentLoader:
import { ComponentLoader } from './classes/classes.mjs';
const cl = new ComponentLoader('path_to_your_component.html');
- Inject a Component:
// first argument is the selector on the component.html seconed argument is the selector on the target page
cl.injectComponent('[data-login-form]', '[data-form]')
.then(() => {
// here you can add javascript if needed
console.log('Component loaded successfully.');
})
.catch((error) => {
console.error('Error:', error);
});
component.html
<form data-login-form data-form>...</form>
target.html
<div data-form></div>