User007
User007

Reputation: 1559

Simple caching in javascript

What potential problem can arise if I am keeping data inside a global var cache = {} ?

Will it be collected by the garbage collector? Can I ensure it's persistent until the end of viewing?

Is there browser built-in functionality I can use so even next time opening the page I have the cached data ready?

Thanks.

Upvotes: 0

Views: 267

Answers (2)

jfriend00
jfriend00

Reputation: 707328

It sounds like you need to understand the lifetime of global data in javascript:

  1. During the lifetime of a given page, a global variable lasts until you clear it's value. It will never be garbage collected. Because it's global, it can never go out of scope.

  2. When the viewer goes to a new page in that window or closes that browser window, all javsacript data for that prior page is freed and is no longer available.

  3. There are three ways to persist data so it can be used in future views of that page or in other pages: 1) Cookies, 2) Local Storage, 3) Server storage. In all of these cases, the data would have to be retrieved from its storage location and put back into javascript.

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 4276

The variable will exist as long as the page remains open. After it is closed (or navigated away from), it will be garbage collected.

If there is very little data in the cache, you can serialize it and store it as a cookie. For larger amounts of data, DOM Storage may be useful but it is not universally supported among browsers.

Upvotes: 1

Related Questions