In your example it should be var retrievedObject = JSON.parse(localStorage.getItem('testObject'))
;. As localStorage can only handle string value pairs by now, it would be worth a try to make up a new Object like this:
{type: "css", blob: "<serverside rendered>", deferred: false}
Here is an example:
var resources = [
{type: "css", blob: ".unknown { color: red; } div { margin: 20px; }", deferred: false}
]
function appendResources(){
var head = document.getElementsByTagName("head")[0];
for(var resourceIndex in resources){
var resource = resources[resourceIndex]
if(resource.type == "css"){
/* https://stackoverflow.com/a/6211716/3244925 */
var element = document.createElement("style");
element.type = "text/css";
element.appendChild(document.createTextNode(resource.blob));
head.appendChild(element)
}
}
}
document.getElementsByTagName("button")[0].addEventListener("click", appendResources);
<div class="unknown">Defaultly, i have no style.</div>
<button>Add style from localStorage</button>
You can fill an array of object like these by your server side implementation and append them to the dom later on. This example only handles CSS and makes no difference for deffered items, as it appends everything to the <head>
, but you get the idea.
I copied the interesting part of this answer: https://stackoverflow.com/a/6211716/3244925
These objects can be saved in the localStorage using: localStorage.setItem('resources', JSON.stringify(resources));
and later on be re used.
Update
I feel the answer to your question may be much simpler. If your .css and .js files are static, you may just make up an array of external resources (urls) and append those urls to the <head>
and <body>
later on, once you loaded them from the localStorage
. This will render this inline styles and javascript useless, and it would be a much cleaner solution.