frenchie
frenchie

Reputation: 51927

loading CSS with jQuery not applying styles to page

I'm loading a CSS file dynamically after the document.ready function fired. This is what I have:

$.get(TheCSSTag.href, function () {

    alert('loaded');
    DoSomething();

}, "text/css");

The problem is that the alert triggers fine (which I assume means the CSS loaded) but the styles aren't applied to the HTML elements.

Note: other solutions that involve creating a CSS tag and appending to the DOM like this document.getElementsByTagName('head')[0].appendChild(TheCSSTag); don't work for me because I need a callback function to execute when the CSS file loaded.

Upvotes: 0

Views: 166

Answers (2)

Aeveus
Aeveus

Reputation: 5382

The thing is... You're not actually telling the browser to use the CSS. You're just asking jQuery to get it for you. Inside the callback of $.get, you need to actually inject it into your page.

Here's an example using jQuery where you read the entire thing and put it into a style tag inside head:

$.when($.get('your_css_file.css')).done(function (response) {
    $('<style />').text(response).appendTo($('head'))
})

Another way would be to simply add the URL to the head:

$('<link /')
    .attr('type', 'text/css')
    .attr('rel', 'stylesheet')
    .attr('href', 'your_css_file.css')
    .appendTo($('head'))

Upvotes: 1

Popnoodles
Popnoodles

Reputation: 28409

You need to add the CSS file to the page. $.get() won't do that for you.

$.get(TheCSSTag.href, function(){

     $('<link>', {rel:'stylesheet', type:'text/css', 'href':TheCSSTag.href}).appendTo('head');
     alert('loaded');
     DoSomething();

}, "text/css");

Please note: without xdomain permissions $.get will only load local files though you can just add them to head without using $.get first.

Upvotes: 1

Related Questions