-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
88 lines (66 loc) · 2.19 KB
/
main.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//Progressive enhancement
console.log(navigator.serviceWorker)
if (navigator.serviceWorker) {
console.log(0, 'SW avaialable')
//Register SW
navigator.serviceWorker.register('sw.js').catch(console.error);
// Giphy cache clean
function giphyCacheClean(giphys) {
// Get service worker registration
navigator.serviceWorker.getRegistration().then(function (req) {
//Only post message to active SW
if (req.active) req.active.postMessage({ action: 'cleanGiphyCache', giphys: giphys })
})
}
}
// Giphy API object
var giphy = {
url: 'https://api.giphy.com/v1/gifs/trending',
query: {
api_key: '54452c59b31e4d14aca213ec76014baa',
limit: 12
}
};
// Update trending giphys
function update() {
// Toggle refresh state
$('#update .icon').toggleClass('d-none');
// Call Giphy API
$.get(giphy.url, giphy.query)
// Success
.done(function (res) {
// Empty Element
$('#giphys').empty();
//Populate array of latest giphys
var latestGiphys = [];
// Loop Giphys
$.each(res.data, function (i, giphy) {
// Add to latest Giphys
latestGiphys.push(giphy.images.downsized_large.url)
// Add Giphy HTML
$('#giphys').prepend(
'<div class="col-sm-6 col-md-4 col-lg-3 p-1">' +
'<img class="w-100 img-fluid" src="' + giphy.images.downsized_large.url + '">' +
'</div>'
);
});
// Inform the SW (if available) of current Giphys
if (navigator.serviceWorker) giphyCacheClean(latestGiphys)
})
// Failure
.fail(function () {
$('.alert').slideDown();
setTimeout(function () { $('.alert').slideUp() }, 2000);
})
// Complete
.always(function () {
// Re-Toggle refresh state
$('#update .icon').toggleClass('d-none');
});
// Prevent submission if originates from click
return false;
}
// Manual refresh
$('#update a').click(update);
// Update trending giphys on load
update();