forked from mdn/sw-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
71 lines (61 loc) · 2.31 KB
/
app.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
// register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
if(reg.installing) {
console.log('Service worker installing');
} else if(reg.waiting) {
console.log('Service worker installed');
} else if(reg.active) {
console.log('Service worker active');
}
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
navigator.serviceWorker.ready.then(function(event) {
console.log("ready", event);
setTimeout(function() {
fetch('https://www.wikipedia.org/portal/wikipedia.org/assets/img/[email protected]',
{headers:{'X-Custom-header': 'bar'}}).then(function(data) {
console.log('fetch on ready complete');
}).catch(function() {
console.log('fetch on ready failed');
})
}, 3000);
});
};
// function for loading each image via fetch() with an added custom header.
function imgLoad(imgJSON) {
// return a promise for an image loading
return new Promise(function(resolve, reject) {
fetch(imgJSON.url, {headers:{'X-Custom-header': 'bar'}}).catch(function() {
console.error("imgLoad fetch failed");
}).then(function(data) {
console.log("imgLoad fetch success");
var arrayResponse = [];
arrayResponse[0] = data;
arrayResponse[1] = imgJSON;
resolve(arrayResponse);
});
});
};
var imgSection = document.querySelector('section');
window.onload = function() {
// load each set of image, alt text, name and caption
for(i = 0; i<=Gallery.images.length-1; i++) {
imgLoad(Gallery.images[i]).then(function(arrayResponse) {
var myImage = document.createElement('img');
var myFigure = document.createElement('figure');
var myCaption = document.createElement('caption');
var imageURL = window.URL.createObjectURL(arrayResponse[0]);
myImage.src = imageURL;
myImage.setAttribute('alt', arrayResponse[1].alt);
myCaption.innerHTML = '<strong>' + arrayResponse[1].name + '</strong>: Taken by ' + arrayResponse[1].credit;
imgSection.appendChild(myFigure);
myFigure.appendChild(myImage);
myFigure.appendChild(myCaption);
}, function(Error) {
console.log(Error);
});
};
};