简体   繁体   中英

loading CSS with jQuery not applying styles to page

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM