Advertisement
Riaaniceman069

Service Worker

May 21st, 2020
2,155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.                     // Service Worker With Custom Caching Strategies Based On File Type
  2.                     // 1. Install               -> Cache Once Then Return Cache
  3.                     // 2. Excluded Files        -> Cache Once Then Return Cache
  4.                     // 3. Final Stage (HTML)    -> Stale While Re-Validate With Fallback Page ( Offline Page ) 
  5.  
  6.                     cacheName = "v'.VERSION.'";
  7.                     var offlineURL = "offline_'.DEFAULT_LANG.'.html";
  8.                     // These Files Will Be Cached By The Service Worker Install Event
  9.                     // These Files Are Only Cached With Install And Then Returned As Cache Always
  10.                     var appShellFiles = [
  11.                       "offline_'.DEFAULT_LANG.'.html",
  12.                       "'.FAVICO16.'",
  13.                       "'.FAVICO32.'",
  14.                       "'.BOOTSTRAP_CSS.'",
  15.                       "'.BOOTSTRAP_JS.'",
  16.                       "'.FONT_AWESOME.'",
  17.                       "'.POPPER.'",
  18.                       "'.CUSTOM_CSS.'",
  19.                       "'.JQUERY.'"
  20.                     ];
  21.                     // Files To Use In Cache First Then Network Strategy, With Caching On Network
  22.                     // These Files Will Only Be Cached Once From Network Then Returned As Cache Always
  23.                     var excludeExts = [
  24.                       ".css",
  25.                       ".js",
  26.                       ".webp",
  27.                       ".png",
  28.                       ".jpg"
  29.                     ];
  30.                    
  31.                     // Install Event
  32.                     self.addEventListener("install", event => {
  33.                         // PreCache App Files
  34.                         //console.log("[Service Worker][Install] PreCahing...");
  35.                         event.waitUntil(
  36.                             caches.open(cacheName)
  37.                             .then(cache => cache.addAll(appShellFiles))
  38.                             .then(self.skipWaiting())
  39.                         );
  40.                     });
  41.                    
  42.                     // Fetch Event
  43.                     self.addEventListener("fetch", event => {
  44.                         const requestedURL = event.request.url;
  45.                         // Allow Local Files Only
  46.                         if (event.request.url.startsWith(self.location.origin)) {
  47.                             var flag = false;
  48.                             // Return All App Files From Cache
  49.                             //console.log("[Service Worker][New Fetch] -> "+requestedURL);
  50.                             appShellFiles.forEach(function(appShellFile){
  51.                                 if(requestedURL.includes(appShellFile)){
  52.                                     flag = true;
  53.                                     //console.log("[Service Worker][AppFiles] Return From Cache -> "+requestedURL);
  54.                                     event.respondWith(
  55.                                         caches.match(event.request).then(cachedResponse => {
  56.                                             if (cachedResponse) {
  57.                                                 return cachedResponse;
  58.                                             }
  59.                                         })
  60.                                     );
  61.                                 }
  62.                             });
  63.                            
  64.                             if(!flag){
  65.                                 //console.log("[Service Worker] Determine Strategy -> "+requestedURL);
  66.                                 var flagb = false;
  67.                                 // Excluded File Extentions
  68.                                 excludeExts.forEach(function(excludeExt){
  69.                                     if(requestedURL.includes(excludeExt)){
  70.                                         //console.log("[Service Worker][Resources] Cache First Then Network -> "+requestedURL);
  71.                                         flagb = true;
  72.                                         event.respondWith(
  73.                                             caches.open(cacheName).then(function(cache) {
  74.                                                 return cache.match(event.request).then(function (response) {
  75.                                                     return response || fetch(event.request).then(function(response) {
  76.                                                         cache.put(event.request, response.clone());
  77.                                                         return response;
  78.                                                     }).catch(function() {
  79.                                                         //console.log("[Service Worker] Resource Not Found -> "+requestedURL);
  80.                                                     })
  81.                                                 });
  82.                                             })
  83.                                         );
  84.                                     }
  85.                                 });
  86.                                 if(!flagb){
  87.                                     // Final Stage ( Stale While Re-Validate )
  88.                                     var fetched = fetch(event.request);
  89.                                     var cached = caches.match(event.request);
  90.                                     var fetchedCopy = fetched.then(resp => resp.clone());
  91.                                     //console.log("[Service Worker][Final Stage] Stale While Re-Validate -> "+requestedURL);
  92.                                     event.respondWith(
  93.                                         Promise.race([fetched.catch(_ => cached), cached])
  94.                                         .then(resp => resp || fetched)
  95.                                         .catch(function(){
  96.                                             return caches.open(cacheName).then(function(cache) {
  97.                                                 //console.log("[Service Worker][Final Stage] Fallback -> "+requestedURL);
  98.                                                 return cache.match(offlineURL);// Fallback Page
  99.                                             });
  100.                                         })
  101.                                     );
  102.                                    
  103.                                     // Update The Cache
  104.                                     event.waitUntil(
  105.                                         Promise.all([fetchedCopy, caches.open(cacheName)])
  106.                                         .then(([response, cache]) => cache.put(event.request, response))
  107.                                         .catch(_ => {/* eat any errors */})
  108.                                     );
  109.                                 }
  110.                             }
  111.                         }
  112.                     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement