28 lines
994 B
JavaScript
28 lines
994 B
JavaScript
// Komponenty HTML loader
|
|
function loadComponent(path, replaceMap = {}) {
|
|
// If path is a full mapped origin used by WebViewAssetLoader, strip it to a relative path.
|
|
const mappedOrigin = 'https://appassets.androidplatform.net/assets/';
|
|
if (path.startsWith(mappedOrigin)) {
|
|
path = path.slice(mappedOrigin.length);
|
|
}
|
|
|
|
// If an absolute path starting with '/' is provided, remove leading slash to make it
|
|
// relative to the current document (works under local http server and WebViewAssetLoader).
|
|
if (path.startsWith('/')) path = path.slice(1);
|
|
|
|
return fetch(path)
|
|
.then(r => {
|
|
if (!r.ok) throw new Error('Failed to load component: ' + path);
|
|
return r.text();
|
|
})
|
|
.then(html => {
|
|
Object.entries(replaceMap).forEach(([key, val]) => {
|
|
html = html.replaceAll(key, val);
|
|
});
|
|
return html;
|
|
});
|
|
}
|
|
|
|
// Przykład użycia:
|
|
// loadComponent('components/header.html', {'{TITLE}': 'Tytuł', '{SUBTITLE}': 'Podtytuł'}).then(html => ...)
|