Adam Lukaszczyk
Adam Lukaszczyk

Reputation: 4926

How to asynchronously load CSS using jQuery?

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?

Upvotes: 22

Views: 36387

Answers (9)

Yvan
Yvan

Reputation: 2699

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.

Upvotes: 0

Dmitry Pashkevich
Dmitry Pashkevich

Reputation: 13516

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);

Upvotes: 44

Alan H.
Alan H.

Reputation: 16568

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.

Upvotes: 0

noamtcohen
noamtcohen

Reputation: 4612

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

Upvotes: 0

ekerner
ekerner

Reputation: 5840

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');

Upvotes: 1

Hendy Irawan
Hendy Irawan

Reputation: 21384

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.

Upvotes: 10

lonesomeday
lonesomeday

Reputation: 237865

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);

Upvotes: 31

Praveen Prasad
Praveen Prasad

Reputation: 32107

jQuery(function(){

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

});

Upvotes: 0

Peter Olson
Peter Olson

Reputation: 142921

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' />");

Upvotes: 20

Related Questions