73

Is there a way to load external CSS files, like we load JS file by using .getScript method and also use the callback function like in .getScript

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "/styles/yourcss.css"
}).appendTo("head");

This Works in FireFox and similar but not in IE.

8 Answers 8

118

In jQuery 1.4:

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "/styles/yourcss.css"
}).appendTo("head");

http://api.jquery.com/jQuery/#jQuery2

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, but how to use callback function like .getScript() once the CSS file is loaded
For me it didn't work in IE8. Here is a working solution stackoverflow.com/questions/805384/… (by user "user406905")
I have just posted how to do this with callback on another question stackoverflow.com/questions/3498647/…
This looks to be an exact copy and paste of the code in the question, the question was asking if there is a equivalent to jQuery.getScript() to which the answer is no.
22

Quick function based on responses.

loadCSS = function(href) {

  var cssLink = $("<link>");
  $("head").append(cssLink); //IE hack: append before setting href

  cssLink.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: href
  });

};

Usage:

loadCSS("/css/file.css");

2 Comments

Thank you... I combined your code with MVC 4 bundles and it worked!
See my answer for added callback, without triggering additional request on the CSS resource. I don't think this IE hack is relevant in 2019.
18
$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "address_of_your_css"
});

5 Comments

Ok, but how to use callback function like .getScript() once the CSS file is loaded
@Starx Please edit your original question to reflect exactly what you need - not only the loading of external CSS files dynamically, but also a callback.
Yay for IE hacks. You second line could be: var css = $('head > :last') yes?
I've adapted this script to be used with jquery 1.12.4 without any problems, FYI.
Will be easier and more intuitive to use appendTo, like this: $("<link>").attr({ rel: "stylesheet", type: "text/css", href: "address_of_your_css" }).appendTo("head");
10

I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

2 Comments

By downloading the external resource (css) as text and dumping it inside <Style> tag, you lose the caching facility of the browser as it cache using the css URL as a cache key.
@AbdulhameedShalabi as Willster explains below, css can still be cached even if it is fetched over ajax. It depends on the original response headers of the resource.
4

    //load css first, then print <link> to header, and execute callback
    //just set var href above this..
    $.ajax({
          url: href,
          dataType: 'css',
          success: function(){                  
                $('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
                //your callback
            }
    });

For Jquery 1.2.6 and above ( omitting the fancy attributes functions above ).

I am doing it this way because I think that this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.

3 Comments

There is no support for this in jQuery (dataType: 'css'), does it work for you?
interesting.. yes it does work for me. I suppose this answer would be more correct without the dataType parameter, I'm not sure why that doesn't cause an error for me. (see related thread about using css dataType: bugs.jquery.com/ticket/10082)
Not efficient, you downloaded the css file but you didn't make use of the downloaded bytes in the "success" callback and then you added the <link> tag.
2

Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).

function loadCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            return $.get(url, function(css) {
                $("<style>" + css + "</style>").appendTo("head");
            });
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

Usage as so:

loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
    function() {
    alert("All resources loaded");
}, function() {
    alert("One or more resources failed to load");
});

Here is another function that will load both CSS and javascript files:

function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            if(url.endsWith(".css")) {
                return $.get(url, function(css) {
                    $("<style>" + css + "</style>").appendTo("head");
                });
            } else {
                return $.getScript(url);
            }
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

3 Comments

Note a negative of this solution, if you are using relative source maps, it won't be found if the css is inlined (as opposed to added via a <link> tag).
By downloading the external resource (css) as text and dumping it inside <Style> tag, you lose the caching facility of the browser as it caches using the css URL as a cache key
@AbdulhameedShalabi no, css can still be cached even if it is fetched over ajax. It depends on the original response headers of the resource.
0

Based on your comment under @Raul's answer, I can think of two ways to include a callback:

  1. Have getScript call the file that loads the css.
  2. Load the contents of the css file with AJAX, and append to <style>. Your callback would be the callback from $.get or whatever you use to load the css file contents.

Comments

-5

$("#pageCSS").attr('href', './css/new_css.css');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.