Service Worker Flashcards
What is a service worker
Service worker is a javascript that runs in a background of a web application
- It does not have access to DOM
- It can intercept network request
Some applications:
* Offline support
* Push Notifications
* Background sync
How to manipulate DOM from service worker
Service worker can not directly manipulate DOM as it runs in background. However, it can use any of below techniques to update DOM
- Caching: SW can intercept the network request and see if the data requested is already cached. If it is then it will return immedietly and DOM will show cached data
- postMessage(): It can use postMessage to send data to DOM, DOM can further use such data
- IndexDB: ID is used to preserve data so that it persists even if service worker is restarted. So SW can store data in IndexDB and DOM can fetch the data
- Websocket: Mainly for chat applications, SW can intercept the network requests and pass the data to DOM
What is IndexedDB
Indexed DB is a NoSQL like data storage that resides in user’s browser. It provides object oriented storage mechanism and complex querying capability.
Features:
* You can store data even when slow network or no network
* Secured compared to cookies
* Provides large data storage capability
* Data is stored for permanently and does not get deleted on browser close
What is webstorage
Webstorage allows to store data locally in browser, and it provides limited capabilities compared to IndexedDB. The size limit is usually around 5 MB and does not provide querying capabilities.
Two types:
1. localStorage: Data is persisted and not get deleted when browser is closed. Need to be removed manually.
2. Session Storage: Data has some TTL or deleted when session is closed
Diifference between Cookies, Web Storage and IndexedDB
Cookies:
* Storage less than 4 KB
* Data is sent to server
* Chances of CSRF attacks
Web Storage:
* Storage less than 4 MB
* Data remains at client side
* Better than cookies
* Two types: 1. Local 2. Session
* Key-Value search capability
IndexedDB:
* Storage around 100 MB
* Data remains at client side
* Offline capabilities
* NoSQL like structure so provide query ability
What is Web worker
Web worker is also used to perform background activities but it has different function than SW. It is mainly used to perform CPU intensive tasks.
* WW can also update DOM with postMessage()
* But it gets terminated more often then SW
* Also it does not intercept.network calls or work in offline mode