I would like to use localStorage
to 'cache' some JS and CSS files in a web app that is primarily used on mobile devices (i.e., bandwidth restrictions). I'm thinking it would work something like this:
setup.js
containing code that checks localStorage
to see if bigScriptFile.js
has been stored previously.
bigScriptFile.js
is downloaded and stored for the next visit.bigScriptFiles.js
is read from localStorage
and loaded/run as if it was downloaded like a normal file (i.e., <script src="http://example.com/bigScriptFile.js"></script>
)What I'm not sure how to do is step 1.1 -- storing the JS file. (I know that I can only store strings in localStorage
and I know how to use JSON.stringify()
.)
Surely it's not as simple as using escape():localStorage.setItem('bigScriptFile', escape('myJScode'))
to store, andunescape(localStorage.getItem['bigScriptFile'])
when retrieving
Even if it is that easy, how do I use JS to get the contents of bigScriptFile.js as a string? Perhaps by making an ajax call to a PHP script that returns the contents?
localStorage can only store Strings, while modern Javascript can also handle binary files. For example, the result of a fetch can be retrieved as a Blob .
It is limited to about 5MB and can contain only strings. LocalStorage is not accessible from web workers or service workers. Cookies have their uses, but should not be used for storage.
IndexedDB offers several benefits over localStorage. For instance, IndexedDB doesn't block the DOM when used with a worker, unlike localStorage. However, localStorage is slightly faster than IndexedDB. The API of localStorage is also much easier to get started with, making it the more popular choice.
Local storage is inherently no more secure than using cookies. When that's understood, the object can be used to store data that's insignificant from a security standpoint.
You should rather put the correct cache headers on js files or look at the HTML5 cache manifest.
W3C specification.
Have you seen http://addyosmani.github.com/basket.js/ might work for what you intended to do
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With