-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrouter.ts
More file actions
46 lines (37 loc) · 1.37 KB
/
router.ts
File metadata and controls
46 lines (37 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
(function () {
if (window.uitgAppContext?.SPARouter) return;
const PLACEHOLDER_ATTR = 'data-placeholder-id';
const TARGET_PLACEHOLDER_ATTR = 'data-target-placeholder-id';
function init() {
window.addEventListener('popstate', () => {
handleRoute(document.location.toString());
});
}
function navigate(url: string) {
history.pushState({}, '', url);
handleRoute(url);
}
function handleRoute(targetUrl: string) {
const url = new URL(targetUrl, window.location.origin);
url.searchParams.append('__PARTIAL', 'true');
$.get(url.href, (markup) => {
const parser = new DOMParser();
const doc = parser.parseFromString(markup, "text/html");
const contentItems = doc.querySelectorAll(`[${TARGET_PLACEHOLDER_ATTR}]`);
contentItems.forEach((content) => {
const targetAttr = content.getAttribute(TARGET_PLACEHOLDER_ATTR);
if (!targetAttr) return;
const placeholder = $(`[${PLACEHOLDER_ATTR}=${targetAttr}]`);
if (placeholder.length) {
placeholder.html(content.innerHTML);
} else {
window.location.reload();
}
});
});
}
window.uitgAppContext.SPARouter = {
init,
navigate
};
})();