user2718671 user2718671 - 1 year ago 72
jQuery Question

How to prevent rendering css when loading stylesheet from local storage?

Following problem - I stored a stylesheet in the local storage. But when I try to load it from there I use

and it seems that the browser will already render the CSS. But I would prefer the browser to treat the parsed CSS as text, then append the text to a style tag.

The Code:

loading the stylesheet from server and store it in local storage

function load_css(url){
url: url,
cache: false,
dataType: 'text',
success: function(res){
$('<style>').attr('id', 'my_style').text(res).prependTo('#my_div');
if (typeof(Storage) !== "undefined" && typeof localStorage !== "undefined" && localStorage !== null && typeof localStorage.setItem === 'function') {
localStorage.setItem("my_style", JSON.stringify(res));
error: function(err){

within another function the styles shall be loaded from local storage if set:

if (typeof(Storage) !== "undefined" && typeof localStorage !== "undefined" && localStorage !== null && localStorage.getItem("my_style") !== null) {
var css = JSON.parse(localStorage.getItem('my_style'));
$('<style>').attr('id', 'my_style').text(css).prependTo('#my_div');
... //load style from server if local storage not available, item not found

Even when I leave out the line with the created style tag the css is being rendered. With this line I see that if I inspect an element the element styles appear twice in the developer tool bar. So how could I prevent the browser from rendering the styles when using
. Maybe there is another method that treats the styles from local storage as plain text?

Answer Source

You are calling this

$('<style>').attr('id', 'my_style').text(res).prependTo('#my_div');   

before storing it. So it's on the document once you get it through ajax, and then on the other code you just put it again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download