Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing branch #6

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# Lab 7 - Starter

Zixian Wang

https://coffee-drinker.github.io/Lab7_Starter/
132 changes: 100 additions & 32 deletions assets/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,45 @@ function initializeServiceWorker() {
// We first must register our ServiceWorker here before any of the code in
// sw.js is executed.
// B1. TODO - Check if 'serviceWorker' is supported in the current browser
// B2. TODO - Listen for the 'load' event on the window object.
// Steps B3-B6 will be *inside* the event listener's function created in B2
// B3. TODO - Register './sw.js' as a service worker (The MDN article
// "Using Service Workers" will help you here)
// B4. TODO - Once the service worker has been successfully registered, console
// log that it was successful.
// B5. TODO - In the event that the service worker registration fails, console
// log that it has failed.
// STEPS B6 ONWARDS WILL BE IN /sw.js

if ("serviceWorker" in navigator) {

// B2. TODO - Listen for the 'load' event on the window object.
window.addEventListener("load", async (event) => {

// Steps B3-B6 will be *inside* the event listener's function created in B2
// B3. TODO - Register '/sw.js' as a service worker (The MDN article
// "Using Service Workers" will help you here)

try {

const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});

console.log ("get to here! ")

// B4. TODO - Once the service worker has been successfully registered, console
// log that it was successful.
if (registration.waiting) {
console.log("Service worker installed");
}
}


// B5. TODO - In the event that the service worker registration fails, console
// log that it has failed.

catch (err) {
console.log("Fail to register")
console.error (err)
}

// STEPS B6 ONWARDS WILL BE IN /sw.js

})
}

}

/**
Expand All @@ -68,38 +98,76 @@ async function getRecipes() {
// EXPOSE - START (All expose numbers start with A)
// A1. TODO - Check local storage to see if there are any recipes.
// If there are recipes, return them.
let localItem = localStorage.getItem('recipes');
if (localItem === null) {
// nothing happens
} else {
return JSON.parse(localItem);
// return localItem;
}

/**************************/
// The rest of this method will be concerned with requesting the recipes
// from the network
// A2. TODO - Create an empty array to hold the recipes that you will fetch
let recipes_arr = [];

// A3. TODO - Return a new Promise. If you are unfamiliar with promises, MDN
// has a great article on them. A promise takes one parameter - A
// function (we call these callback functions). That function will
// take two parameters - resolve, and reject. These are functions
// you can call to either resolve the Promise or Reject it.
/**************************/
// A4-A11 will all be *inside* the callback function we passed to the Promise
// we're returning
/**************************/
// A4. TODO - Loop through each recipe in the RECIPE_URLS array constant
// declared above
// A5. TODO - Since we are going to be dealing with asynchronous code, create
// a try / catch block. A6-A9 will be in the try portion, A10-A11
// will be in the catch portion.
// A6. TODO - For each URL in that array, fetch the URL - MDN also has a great
// article on fetch(). NOTE: Fetches are ASYNCHRONOUS, meaning that
// you must either use "await fetch(...)" or "fetch.then(...)". This
// function is using the async keyword so we recommend "await"
// A7. TODO - For each fetch response, retrieve the JSON from it using .json().
// NOTE: .json() is ALSO asynchronous, so you will need to use
// "await" again
// A8. TODO - Add the new recipe to the recipes array
// A9. TODO - Check to see if you have finished retrieving all of the recipes,
// if you have, then save the recipes to storage using the function
// we have provided. Then, pass the recipes array to the Promise's
// resolve() method.
// A10. TODO - Log any errors from catch using console.error
// A11. TODO - Pass any errors to the Promise's reject() function
return new Promise(async (resolve, reject) => {


/**************************/
// A4-A11 will all be *inside* the callback function we passed to the Promise
// we're returning
/**************************/
// A4. TODO - Loop through each recipe in the RECIPE_URLS array constant
// declared above
for (let i = 0; i < RECIPE_URLS.length; i++) {
//????????????????????????????????????????????????????????????????????????????????????????????????????????????????


// A5. TODO - Since we are going to be dealing with asynchronous code, create
// a try / catch block. A6-A9 will be in the try portion, A10-A11
// will be in the catch portion.
try {
// A6. TODO - For each URL in that array, fetch the URL - MDN also has a great
// article on fetch(). NOTE: Fetches are ASYNCHRONOUS, meaning that
// you must either use "await fetch(...)" or "fetch.then(...)". This
// function is using the async keyword so we recommend "await"
let fetched_url = await fetch(RECIPE_URLS[i])


// A7. TODO - For each fetch response, retrieve the JSON from it using .json().
// NOTE: .json() is ALSO asynchronous, so you will need to use
// "await" again
let fetched_json = await fetched_url.json()


// A8. TODO - Add the new recipe to the recipes array
recipes_arr.push(fetched_json)

// A9. TODO - Check to see if you have finished retrieving all of the recipes,
// if you have, then save the recipes to storage using the function
// we have provided. Then, pass the recipes array to the Promise's
// resolve() method.
if (i == RECIPE_URLS.length - 1) {
// console.log (typeof (recipes_arr))
addRecipesToDocument(recipes_arr)
resolve(recipes_arr)
}

} catch (err) {
// A10. TODO - Log any errors from catch using console.error
console.error(err)
// A11. TODO - Pass any errors to the Promise's reject() function
reject(err)
}
}
});
}

/**
Expand Down
35 changes: 30 additions & 5 deletions sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ self.addEventListener('install', function (event) {
caches.open(CACHE_NAME).then(function (cache) {
// B6. TODO - Add all of the URLs from RECIPE_URLs here so that they are
// added to the cache when the ServiceWorker is installed
return cache.addAll([]);

return cache.addAll([
'https://introweb.tech/assets/json/1_50-thanksgiving-side-dishes.json',
'https://introweb.tech/assets/json/2_roasting-turkey-breast-with-stuffing.json',
'https://introweb.tech/assets/json/3_moms-cornbread-stuffing.json',
'https://introweb.tech/assets/json/4_50-indulgent-thanksgiving-side-dishes-for-any-holiday-gathering.json',
'https://introweb.tech/assets/json/5_healthy-thanksgiving-recipe-crockpot-turkey-breast.json',
'https://introweb.tech/assets/json/6_one-pot-thanksgiving-dinner.json',
]);
})
);
});
Expand All @@ -34,7 +42,24 @@ self.addEventListener('fetch', function (event) {
/*******************************/
// B7. TODO - Respond to the event by opening the cache using the name we gave
// above (CACHE_NAME)
// B8. TODO - If the request is in the cache, return with the cached version.
// Otherwise fetch the resource, add it to the cache, and return
// network response.
});
event.respondWith(caches.open(CACHE_NAME).then((cache) => {



// B8. TODO - If the request is in the cache, return with the cached version.
// Otherwise fetch the resource, add it to the cache, and return
// network response.

return cache.match(event.request).then((cachedResponse) => {
return cachedResponse || fetch(event.request).then((fetchedResponse) => {
// Add the network response to the cache for future visits.
// Note: we need to make a copy of the response to save it in
// the cache and use the original as the request response.
cache.put(event.request, fetchedResponse.clone());

// Return the network response
return fetchedResponse;
});
});
}));
})