LiterallyNoOne
LiterallyNoOne

Reputation: 151

What is the lifetime for a variable stored in service worker?

For example i declare a global variable in service worker like

var cacheVersion  = "v1"; // line no 1 in sw.js

what is the lifetime for this variable?. will this variable be there until service worker gets unregistered or will it be deleted if the service worker was in idle state.

Upvotes: 15

Views: 4664

Answers (2)

run_the_race
run_the_race

Reputation: 2408

I think @pl4n3th only paints half the picture.

I am using the term "shutdown" to mean the browser still has the service worker registered, but maybe you having been browsing the site for awhile, so it frees it from memory.

Yes the global state is lost when the browser shuts down the service worker. However, when it resumes it, all code at the top level is run again, and hence it will execute this line (if its at the top level):

var cacheVersion  = "v1"; // line no 1 in sw.js

Which means now you have the cacheVersion variable available again. Since its a constant, no problem.

However if say in a fetch callback, you set cacheVersion = "v2". When the service worker is next shutdown, then resumed, the global state will be lost, it will run the javascript again with the top level instruction, hence cacheVersion will once again be "v1".

Upvotes: 8

pl4n3th
pl4n3th

Reputation: 131

Any variable stored inside a service worker will only live as long as the service worker. As soon as the browser kills it, your variable is gone. If you want to persist a value, use either indexedDb (accessible by the service worker) or LocalStorage (DOM only access so you'll need to pass it to the service worker by postMessage)

Upvotes: 4

Related Questions