使用 localStorage 保存整个文件
我想使用 localStorage
在主要用于移动设备的 Web 应用程序中“缓存”一些 JS 和 CSS 文件(即带宽限制)。我认为它会像这样工作:
- 页面加载一个小的
setup.js
,其中包含检查localStorage
以确定是否bigScriptFile.js
的代码code> 之前已存储。- 如果未存储,则会下载并存储
bigScriptFile.js
以供下次访问。 - 如果已存储,则从
localStorage
读取bigScriptFiles.js
并加载/运行,就像下载普通文件一样(即<脚本 src="http://example.com/bigScriptFile.js">
)
- 如果未存储,则会下载并存储
我不知道该怎么做是步骤 1.1——存储 JS 文件。 (我知道我只能将字符串存储在 localStorage
中,并且我知道如何使用 JSON.stringify()
。)
当然它不像使用 escape() 那么简单:< br> localStorage.setItem('bigScriptFile', escape('myJScode'))
存储,以及
检索时 unescape(localStorage.getItem['bigScriptFile'])
即使这么简单,我如何使用 JS 来获取 bigScriptFile.js 的内容作为字符串?也许通过对 PHP 脚本进行 ajax 调用来返回内容?
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:
- The page loads with a small
setup.js
containing code that checkslocalStorage
to see ifbigScriptFile.js
has been stored previously.- If it's not stored,
bigScriptFile.js
is downloaded and stored for the next visit. - If it has been stored, then
bigScriptFiles.js
is read fromlocalStorage
and loaded/run as if it was downloaded like a normal file (i.e.,<script src="http://example.com/bigScriptFile.js"></script>
)
- If it's not stored,
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将正确的缓存标头放在 js 文件上,或者查看 HTML5 缓存清单。
W3C 规范。
You should rather put the correct cache headers on js files or look at the HTML5 cache manifest.
W3C specification.
您是否看到 http://addyosmani.github.com/basket.js/ 可能适用于你打算做什么
Have you seen http://addyosmani.github.com/basket.js/ might work for what you intended to do