简体   繁体   中英

HTML5 LocalStorage store executable scripts

I am developing hybrid app which contains it's own local html & JS file. However, sometime there would be a need to load some small executable JS scripts and even CSS from server. Currently I am doing it with $.getScript and it works fine.

To enable the app to work offline, I am thinking to use Angular cache to store json data and images. However, how can I store executable script maybe with localStorage so that it can be later use in offline mode?

LocalStorage stores text so you can indeed store JS code (which is just text) there.

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.

Here's a working example: 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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