Is there a $.getScript
equivalent in jQuery, but for loading stylesheets?
-
see this:: http://stackoverflow.com/a/3994218/350858 – Sudhir Bastakoti Feb 17 '13 at 10:04
-
1You can easily load and inject CSS, but firing a callback when the CSS has been loaded AND applied to the DOM is close to impossible. You might need to setup a test element, make the CSS apply some styles, then test using interval when that element has the styles applies by the CSS. – David Hellsing Feb 17 '13 at 10:16
5 Answers
CSS is not a script, so you dont have to "execute" it in the sense of script execution.
Basically a <link>
tag created on the fly and appended to the header should suffice, like
$('<link/>', {
rel: 'stylesheet',
type: 'text/css',
href: 'path_to_the.css'
}).appendTo('head');
or
var linkElem = document.createElement('link');
document.getElementsByTagName('head')[0].appendChild(linkElem);
linkElem.rel = 'stylesheet';
linkElem.type = 'text/css';
linkElem.href = 'path_to_the.css';
if you want to do it without jQuery.
The browser will respond to the change in the DOM and update your page layout accordingly.
EDIT:
I have read that old Internet Explorer has trouble with this, and you might need to do it like in answer to make it work:
https://stackoverflow.com/a/2685639/618206
EDIT2:
Reading the file content and putting it inline (between <style>
tags) is also a valid solution, but that way the CSS will not be cached by the browser.

- 1
- 1

- 7,756
- 6
- 54
- 86
-
3This is not really an equivalent, since there is no callback for when the CSS is "ready". – David Hellsing Feb 17 '13 at 10:17
-
That is true. If you want to get a callback, you can use getScript, and insert the contents inline. – vinczemarton Feb 17 '13 at 10:27
-
that is an option, but it’s still not reliable (depending on usage). Even if you know that the CSS file has loaded it doesn’t mean that it’s styles has been applied to the DOM. – David Hellsing Feb 18 '13 at 07:29
-
Keep in mind, that even getScript does not guarantee that the callback will be called after the script execution. For reference: http://api.jquery.com/jQuery.getScript/ I'm not sure if you have any way to tell if a style has been applied yet. – vinczemarton Feb 18 '13 at 08:25
I have created an alternative to $.getScript
that handles stylesheets. I called it $.getStylesheet for obvious reasons.
It implements the $.Deferred
object, which means you can chain things like so:
$.when($.getStylesheet('css/main.css'), $.getScript('js/main.js'))
.then(function () {
console.log('the css and js loaded successfully and are both ready');
}, function () {
console.log('an error occurred somewhere');
});
Here is the little function for $.getStylesheet. It is just hosted on Github gist, so I can update it if I need to.

- 1,399
- 19
- 21
-
Adding a `` to the DOM is near instantaneous. Why wrap it in a deferred? – vinczemarton Sep 22 '16 at 09:15
-
@SoonDead it's to emulate the same API. Without the `$.Deferred` You could not use `$.when` at all. – james2doyle Sep 22 '16 at 19:21
-
I still don't get why would you want to wrap it in a when. You are actually better off moving the `$.getStylesheet` line before the when and get the exact same result. After that you can take an other step to unwrap it from the deferred and still get the exact same result. – vinczemarton Sep 23 '16 at 06:13
-
@SoonDead Firstly, you don't have to use `when`, it is just an example of why you would want to use this technique. Say you want to make a request to 2 scripts and 2 stylesheets and you want to wait till all that is done, then do something else. This is an approach to do that in a clean and succinct way. – james2doyle Sep 23 '16 at 18:29
-
2Do note, that you don't complete your deferred when "all that is done". You complete your deferred when the link tag is added to the dom. This does not guarantee anything to be done. – vinczemarton Sep 24 '16 at 07:45
you can use same method $.getScript to "download" style sheet, since $.getScript actually is just another HTTP request. but it will be a bit wired since css is not executable.

- 2,257
- 14
- 9
-
Relying on the browser to correct your code rather than doing it properly in the first place doesn't seem like good practice to me... – AStopher May 16 '22 at 17:11
Here is a function that will load CSS files with a success or failure callback. I think this approach is better than the accepted answer 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();
});
}

- 2,526
- 1
- 32
- 32
If you want no cache
var date = new Date().getTime();
document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="/templates/primary/style/edit_styles.css?='+date+'">';

- 13
- 4
-
To help people understand your answer better, please provide some extra information along with the code you shared. – Sally loves Lightning Jul 27 '23 at 18:36