简体   繁体   English

HTML5 LocalStorage存储可执行脚本

[英]HTML5 LocalStorage store executable scripts

I am developing hybrid app which contains it's own local html & JS file. 我正在开发混合应用程序,其中包含它自己的本地html和JS文件。 However, sometime there would be a need to load some small executable JS scripts and even CSS from server. 但是,有时需要从服务器加载一些小的可执行JS脚本,甚至CSS。 Currently I am doing it with $.getScript and it works fine. 目前,我正在使用$.getScript ,并且工作正常。

To enable the app to work offline, I am thinking to use Angular cache to store json data and images. 为了使该应用程序能够脱机工作,我正在考虑使用Angular缓存来存储json数据和图像。 However, how can I store executable script maybe with localStorage so that it can be later use in offline mode? 但是,如何将可执行脚本与localStorage一起存储,以便以后可以在脱机模式下使用?

LocalStorage stores text so you can indeed store JS code (which is just text) there. LocalStorage存储文本,因此您确实可以在其中存储JS代码(仅仅是文本)。

You'd just have to load it form LocalStorage and then either execute it with eval() or create a <script> tag and insert the script into it. 您只需要从LocalStorage加载它,然后使用eval()执行它或创建一个<script>标记并将脚本插入其中即可。

Here's a working example: http://jsfiddle.net/jfriend00/1rLcaroc/ 这是一个工作示例: http : //jsfiddle.net/jfriend00/1rLcaroc/

And, the code for that is this: 并且,代码是这样的:

var str = "alert('hello');";

document.getElementById("test").addEventListener("click", function() {
    localStorage.setItem("code", str);

    var code = localStorage.getItem("code");
    eval(code);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM