0

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.

5
  • There's nothing in your code that shows the CSS is being added to the document, or does $.get() do that if you add "text/css" there? Commented Jun 19, 2014 at 18:30
  • 1
    Loading CSS file dynamically is usually a bad idea. What are you trying to achieve? Commented Jun 19, 2014 at 18:34
  • @AnthonyGarcia: the css is loaded from the client based on the screen resolution. Commented Jun 19, 2014 at 19:04
  • @frenchie: Did you considered media queries? Commented Jun 19, 2014 at 19:07
  • @AnthonyGarcia: no, the name of the CSS is determined at runtime. Media queries won't work for that. Commented Jun 19, 2014 at 19:12

2 Answers 2

1

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'))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.