简体   繁体   中英

Javascript File from Local Storage

I have a large JavaScript file that I'd rather not send to the client on each request and it's too large for the browser to cache.

My thought is that I will save the file to HTML5 local storage and attempt to retrieve it. If the file is found then I'd like to link/import/export(I don't know the proper terminology) it into the same scope that a html src tag would.

My question is: how do I take a file that I've pulled from local storage and get my webpage to recognize it as a JavaScript file that was included via src tag? (minus the logic for pulling the file from storage)

My question is: how do I take a file that I've pulled from local storage and get my webpage to recognize it as a JavaScript file that was included via src tag?

Two possible ways (amongst maybe others):

  • create a script element, and assign your JS code as the “text content” of that element before appending it to the DOM. “Text content” in quotes here, because it is not as simple as it sounds cross-browser – see fe Javascript script element set inner text , Executing elements inserted with .innerHTML , or

  • assign your script code to the src attribute of a script element via a Data URI , data:text/javascript,… – but that approach has several disadvantages as well, also mostly in older IE (size limitation; only “non-navigable” content, meaning no scripts). But depending on your target environment that might well work. You will not necessarily need to base64 encode the script code, URL-percent-encoding via encodeURIComponent should work as well.

Take a look at this:

http://jsfiddle.net/611e96mz/1/

var tag = getId('testjs'),
    a = getId('a'),
    b = getId('b'),
    c = getId('c'),
    script;

a.addEventListener('click', function () {
    localStorage.setItem('js', tag.innerHTML);
});

b.addEventListener('click', function () {
    script.textContent = localStorage.getItem('js');
});

c.addEventListener('click', function () {
    document.body.appendChild(script);
    alertMe();
});


var script = document.createElement("script");
script.type = "text/javascript";


function getId(x) {
    return document.getElementById(x);
}

You can use JSON to stringfy your file content and put it on localstorage.

var content = JSON.stringify([1, "some info"]);       // '[1,"some info"]'

localStorage.setItem('fileContent', content);

// Retrieve
var content = localStorage.getItem('fileContent');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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