Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a stylesheet dynamically

After the document.ready event fires, I load the stylesheet dynamically based on the user's resolution. This is what works in Chrome, Firefox and IE:

var TheFileName = '/SomeDirectory/SomeFileName.css';

if (document.createStyleSheet) { 

    //finally found something IE got right
    document.createStyleSheet(TheFileName);

} else {

    $('<style id="TestCSS" type="text/css"></style>').appendTo('head');

    $.get(TheFileName , function (TheCSS) {

        $("#TestCSS").append(TheCSS);
    });
}

The problem is that it doesn't work in Safari. I don't have a mac so I don't have the console error but all I know is that the stylesheet doesn't get added. What do I need to change to make it work in Safari?

PS: I don't want to use media queries.

Edit

I initially had a function that used a <link> tag that was added. My page is entirely dynamically generated and the problem is that adding the stylesheet after the DOM is rendered makes the elements unstyled if you use a <link> tag. So what I do is use a setTimeout to check for $('#TestCSS').length to see if the stylesheet loaded and then I fire the functions that create the HTML. With a tag, there's no way of knowing when the CSS is attached.

like image 694
frenchie Avatar asked Feb 13 '23 02:02

frenchie


1 Answers

Why not just insert the stylesheet as a link tag, instead of loading it with ajax, should be cross-browser ?

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.href = '/SomeDirectory/SomeFileName.css';
document.head.appendChild(link);
like image 161
adeneo Avatar answered Feb 15 '23 10:02

adeneo