22

I want to use jQuery to asynchronously load CSS for a document.

I found this sample, but this doesn't seem to work in IE:

<script type="text/javascript" src="/inc/body/jquery/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        $('<link>', {
            rel: 'stylesheet',
            type: 'text/css',
            href: '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css'
        }).appendTo('head');
        $.getScript("/inc/body/jquery/js/jquery-ui-1.8.10.custom.min.js", function(){
        });
    });
</script>

Basically I want to load jQuery UI after the all other data, images, styles, etc load to the page.

The $.getScript works great for JS file. Only problem is with CSS in IE.

Do you know a better solution?

2
  • Does it work if you make it $('<link/>'...? I.e. add a forward slash. Commented Mar 3, 2011 at 21:20
  • 1
    I'm not sure what you mean by asynchronous...do you perhaps mean dynamic? Commented Mar 3, 2011 at 21:27

9 Answers 9

45

Here's a method for asynchronous stylesheet loading that doesn't block page render that worked for me:

https://github.com/filamentgroup/loadCSS/blob/master/loadCSS.js

Reduced example of the code linked above, based on lonesomeday's answer

var stylesheet = document.createElement('link');
stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
// temporarily set media to something inapplicable to ensure it'll fetch without blocking render
stylesheet.media = 'only x';
// set the media back when the stylesheet loads
stylesheet.onload = function() {stylesheet.media = 'all'}
document.getElementsByTagName('head')[0].appendChild(stylesheet);
Sign up to request clarification or add additional context in comments.

4 Comments

!!This works best for me (considering pageSpeed insights)
Another option is to set rel=preload, don't touch the media, then in onload you set rel=stylesheet. But the main idea is great :-)
Is this the way to go in 2025 or has this been incorporated into the Web standard through some API?
30

The safe way is the old way...

var stylesheet = document.createElement('link');
stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(stylesheet);

6 Comments

Thanks, but I'd rather prefer to do this in jQuery.
Why is this preferable to jQuery? You mention this is the "safe" way. What makes it safer than the accepted answer (assuming of course that jQuery is present)?
RequireJS.org docs specifically refer to this approach: requirejs.org/docs/faq-advanced.html#css
As a rule of thumb: Pure JS is always better, but I don't see how this solution solves the issue of not knowing when the CSS file has finished loading.
Let me tell you why this approach is more efficient than jQuery... Its because if you load it via jQuery, you will have to wait until jQuery is loaded but with this approach you won't need to wait for jQuery and you can load jQuery, CSS and other scripts in parallel
|
19

This should work in IE:

$("head").append("<link rel='stylesheet' type='text/css' href='/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css' />");

7 Comments

The reverse should work, as well: $('<link .../>').appendTo($('head')). This would allow you to chain the link element, rather than the head element, if you wanted to do something else with it after appending it to <head>.
According to this (stackoverflow.com/questions/5085228/…), append does NOT behave asynchronously.
@ElHaix That's true, but I think the OP misunderstood the word "asynchronously" and really meant "dynamically".
@PeterOlson - Looking at yterium.net/jQl-an-asynchronous-jQuery-Loader - could you actually load up your CSS asynch?
Right, this is not asynchronous.
|
10

As mentioned in RequireJS docs, the tricky part lies not in loading the CSS:

function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}

but in knowing when/whether the CSS has loaded successfully, as in your use case " I want to load jQuery UI after the all other data, images, styles, etc load".

Ideally RequireJS could load CSS files as dependencies. However, there are issues knowing when a CSS file has been loaded, particularly in Gecko/Firefox when the file is loaded from another domain. Some history can be found in this Dojo ticket.

Knowing when the file is loaded is important because you may only want to grab the dimensions of a DOM element once the style sheet has loaded.

Some people have implemented an approach where they look for a well known style to be applied to a specific HTML element to know if a style sheet is loaded. Due to the specificity of that solution, it is not something that would fit will with RequireJS. Knowing when the link element has loaded the referenced file would be the most robust solution.

Since knowing when the file has loaded is not reliable, it does not make sense to explicitly support CSS files in RequireJS loading, since it will lead to bug reports due to browser behavior.

Comments

1

As per Dynamically loading css stylesheet doesn't work on IE:

You need to set the href attr last and only after the link elem is appended to the head.

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

Comments

0
$.get("path.to.css",function(data){
    $("head").append("<style>"+data+"</style>");
});

2 Comments

Caution: this may not work if your css file is hosted crossdomain (Browser restrictions).
^ this is true for every http request
0

None of the solutions here actually load the CSS file without blocking page render - which is typically what is meant by “asynchronously.” (If the browser is waiting for something and preventing the user from interacting with the page, the situation is by definition synchronous.)

Examples of synchronous and asynchronous loading can be found here:

http://ajh.us/async-css

I have found that using a setTimeout to defer loading seems to help.

1 Comment

Not true. Dmitry Pashkevich's solution does not block.
0

Another option with very little inline Javascript:

<link
    rel="preload"
    href="/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css"
    as="style"
    onload="this.onload = null; this.rel = 'stylesheet';"/>

Browser will load the file without blocking, then on load it will switch it to the correct rel=stylesheet, which will interpret the CSS file.

Comments

-1
jQuery(function(){

jQuery('head').append('<link href="/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css" rel="stylesheet" type="text/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.