-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspa.js
71 lines (66 loc) · 1.57 KB
/
spa.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// default method:
$(window).on('load hashchange', function(e) {
try {
SPARouter_hash(window.location.hash);
} catch (err) {
console.error(err)
SPANav('./views/500.html')
}
});
// less recommended technique:
$(document).on('click', '.nav a', function(e) {
e.preventDefault();
try {
const rootDir = '/SPA'
SPARouter_url(e.target.pathname);
history.pushState('', '', rootDir + e.target.pathname)
} catch (err) {
console.error(err)
SPANav('./views/500.html')
}
})
// default method:
function SPARouter_hash(page) {
switch(page) {
case '':
case '#':
case '#home':
SPANav('./views/home.html');
break;
case '#about':
SPANav('./views/about.html');
break;
case '#contact':
SPANav('./views/contact.html');
break;
default:
SPANav('./views/404.html');
}
}
// less recommended technique:
function SPARouter_url(page) {
switch(page) {
case '':
case '/':
case '/home':
SPANav('./views/home.html');
break;
case '/about':
SPANav('./views/about.html');
break;
case '/contact':
SPANav('./views/contact.html');
break;
default:
SPANav('./views/404.html');
}
}
function SPANav(to) {
$.get(to, function(pageContent) {
$('.content').html(pageContent);
}).fail(failedGet)
}
function failedGet() {
const refresh = '<a class="refreshpage" href=".">refresh page</a>'
$('.content').html('Oops, something went wrong, make sure you are online.<br>' + refresh);
}