Service Worker

From MgmtWiki
Jump to: navigation, search

Full Title or Meme

A Service Worker, is also a part of what is defined by the World Wide Web Consortium (W3C) as a Web Worker, is a JavaScript executed from an Web Site that runs in the background, independently of user-interface scripts that could be executing in the HTML page.[1]

Context

  • The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.
  • The W3C and the WHATWG started in 2010 the process of developing a definition for an application programming interface (API) for web workers.[1]
  • Service workers are a proxy between the browser and the network. By intercepting requests made by the document, service workers can redirect requests to a cache, enabling offline access. Web workers (from Web Apps) are general-purpose scripts that enable us to offload processor-intensive work from the main thread.

Problems

  • Native mobile apps deliver rich experiences and high performance, purchased at the expense of storage space, lack of real-time updates, and low search engine visibility.[2]
  • Traditional web apps suffer from the inverse set of factors: lack of a native compiled executable, along with dependence on unreliable and potentially slow web connectivity.

Solution

  • Service worker script act as the extra layer between website requests and internet servers. It makes caching any content easier whenever visitor tries to access the Progressive Web App enabled page. The information is further saved locally on the device of user.
  • The standards envision web workers as long-running scripts that are not interrupted by user-interface scripts (scripts that respond to clicks or other user interactions). Keeping such workers from being interrupted by user activities should allow Web pages to remain responsive at the same time as they are running long tasks in the background.
  • Service workers can use multi-core CPUs more effectively than the single thread available in the web browsers.[3]
  • Basic Service Worker Sample from Google to pre-cache script and other files for Web App.

Troubleshooting

  • using sw-precache to generate a service worker with Polymer CLI build process, so it's intended to update the hash of updated files to signal a need to update the cache. But updated content is not being replaced in cache, so it's getting an old version if refreshed with ctrl+r but the new version if refreshed with ctrl+shift+r. A reason for that can be that the service worker is not being updated.
    • sw-precach has been superseded by Workbox which generates hashes for the files you want to precache and adds those to the source code of your service worker (I don't know if sw-precache works the same way, Jeff's answer suggests it does). If any of the files you want to precache change -- and you re-run your build -- the updated hashes in your service worker are updated which pretty much guarantees the service worker will be "at least one byte different".
    • When you reload (ctrl-r) or re-visit your app the browser will fetch again the service worker that was registered for it. And, if that service worker has changed, it will be "queued up" to manage the app. But it won't start managing the app until you close all tabs with the app open, and then open a new one.
    • When you hard refresh (shift-ctrl-r) it’ll always load without a controller which is not the same as using your new service worker.
    • For testing during development, I use skip waiting in devtools to make the new service worker replace the old one without waiting for me to close all the tabs.
    • there is a 1 day (24hr) built-in limit for the browser to look for updates to the service worker, but what you need to be mindful of is you still need to call .update() on your ServiceWorkerRegistration object otherwise the original version of the file will be used.
    • While testing changes in Chrome, I always right-click on the refresh button and select 'Empty Cache and Hard Reset' (options are available when developer tools are open) when working on my service worker script.

Comparing to a Web App

Since both of these concepts derive from JavaScript loaded from a Web Site the differences between a Service Worker and a Web App in the context of the Chrome browser are described below. There is also the idea of a web worker as described on this site. The web worker is typically used to off-load some long running tasks from the main java script code and will not be further discussed here.

Service Worker

  - A **service worker** is a specialized JavaScript asset that acts as a proxy between web browsers and web servers.
  - Its primary purposes are to **improve reliability** and **boost page performance**.
  - Key features of service workers include:
    - **Offline Access**: Service workers allow websites to function even when the user is offline.
    - **Caching Mechanism**: They provide access to a **JavaScript-driven caching API**, separate from the regular HTTP cache. This enables custom caching logic for network requests.
    - **Lifecycle**: Service workers progressively enhance existing websites through a lifecycle similar to platform-specific applications. They don't break baseline functionality for users on browsers that don't support service workers.
    - **Background Execution**: Service workers run in the background, separate from the browser UI thread, making them suitable for tasks like caching and push notifications.
    - **Intercepting Network Requests**: They can intercept network requests via the `fetch` event.
    - **Push Notifications**: Service workers can listen for Push API events in the background via the `push` event.
  - To view a list of running service workers, enter `chrome://serviceworker-internals/` in your address bar.[4]

Advantages of Service Workers

  • Offline Access: Service workers enable websites to function even when the user is offline. They can cache resources and serve them from the cache during network interruptions.
  • Improved Performance: By caching assets, service workers reduce the need for repeated network requests, leading to faster load times.
  • Background Execution: Service workers run independently in the background, separate from the browser UI thread. This allows them to handle tasks like caching and push notifications without affecting the main user interface.
  • Custom Caching Logic: Developers have fine-grained control over caching strategies, allowing them to tailor caching behavior to their specific use cases.
  • Push Notifications: Service workers can listen for push notification events and display notifications to users even when the website is not open.

Disadvantages of Service Workers

Complexity: Implementing and managing service workers can be complex. Developers need to handle scenarios like cache invalidation, version updates, and handling different types of requests. Browser Support: While most modern browsers support service workers, older browsers may not. Ensuring graceful degradation for users on unsupported browsers can be challenging. Security Considerations: Service workers operate in a privileged context, which means they can intercept network requests and potentially introduce security risks if not handled carefully. Caching Challenges: Developers need to strike a balance between caching frequently used resources and avoiding excessive storage usage. Incorrect caching strategies can lead to unexpected behavior. Debugging: Debugging issues related to service workers can be tricky, especially when dealing with background processes.

Web App

  - A **web app** refers to a web-based application that provides functionality similar to native applications.
  - It runs within a web browser but offers an **app-like experience** to users.
  - Characteristics of web apps include:
    - **Responsive Design**: Web apps adapt to different screen sizes and devices.
    - **User Interaction**: They allow users to perform tasks, interact with content, and store data.
    - **URL Access**: Web apps are accessible via URLs and don't require installation from an app store.
    - **Progressive Web Apps (PWAs)**: These are a specific type of web app that leverages modern web technologies to provide an enhanced experience, including offline access, push notifications, and installation on the user's home screen.
  - Unlike service workers, which operate in the background, web apps are directly visible to users.

Advantages

  • Web apps provide a consistent user experience across devices, are accessible via URLs, and don’t require installation but to enable it.
  • Progressive Web Apps (PWAs) enhance web apps by adding features like offline access and push notifications.

Disadvantages

  • Web apps may not have the same level of performance as Native Apps, lack access to certain device features, and rely on the browser environment.

In summary, service workers enhance website functionality, while web apps provide an app-like experience within the browser. For related material see:

References

  1. 1.0 1.1 Web Workers Web Hypertext Application Technology Working Group (2010-06-03) http://www.whatwg.org/specs/web-workers/current-work/
  2. Learn Everything About Progressive Web Apps. HTML Panda https://www.htmlpanda.com/blog/learn-everything-about-progressive-web-apps/
  3. HTML Living Standard (2017-01-30) https://html.spec.whatwg.org/multipage/workers.html#delegation
  4. Chrome for Developers, Service worker overview https://developer.chrome.com/docs/workbox/service-worker-overview/

Other References