7

I'm using local storage to store some data: the user makes ajax requests to get information and I'm storing the result in storage so that next time he requests the same info, I first look in storage to see if it's there.

Now I'm realizing it's actually more efficient to keep that data in an object in memory, and loop over that when needed, rather then loop over local storage. So as I'm moving some data from local storage to an in-memory object, I'm wondering if the window.unload event can be reliably used to write the content of that cache object to local storage on disk, and then retrieve it back using the onload event?

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 1
    No, that's not reliable even if it often works. But writing in localStorage is fast, can't you simply dump your object in localStorage each time it changes (but loading it only on page load) ? – Denys Séguret Dec 02 '12 at 17:11
  • @dystroy: can you show me how to do this? That would mean that I'd need to be able to listen to changes in the object; how do I code that? – frenchie Dec 02 '12 at 21:48
  • I would be interested in an update after 8 years now. It seems really elegant to rely on an event (unload) to persist my app state. – ruben.moor Apr 07 '21 at 21:22

1 Answers1

2

window.unload may not be invoked under a number of circumstances, for instance if the user closes the tab or if the browser crashes. Why not save the data to localStorage periodically, as a precaution?

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • And not every browser supports window.unload. – Biketire Dec 02 '12 at 17:13
  • ^ Yes, I recall having problems with Mobile Safari a while back. – Jim Blackler Dec 02 '12 at 17:15
  • Well the problem with saving the data periodically is that if the data changes on the page, you must also synchronize the data in the storage. That's actually the reason I decided to remove the cache from storage. – frenchie Dec 02 '12 at 17:25
  • Source? Can't see this in the [spec](https://w3c.github.io/uievents/#event-type-unload) or on the [MSDN page](https://developer.mozilla.org/en-US/docs/Web/Events/unload). – John Weisz Aug 07 '18 at 09:02