3

I am trying to append a CSS file to the current HTML page like this:

    var css = jQuery("<link>");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "http://domain.com/chron/css/jquery.gritter.css"
    });
    $("head").append(css);

Once the css file has been downloaded, I want to call a particular function. I thought I would just put the function call after the $('head').append(css); line but am not sure if this will guarantee that the css file will first be downloaded before calling the function. Can someone please tell me how to do this?

2 Answers 2

4

How about retrieving via AJAX and placing it in a STYLE element:

$.ajax( {
    url: 'http://domain.com/chron/css/jquery.gritter.css'
    dataType: 'text'
    success: function( data )
    {
        $( '<style>' )
            .attr( 'type', 'text/css' )
            .text( data )
            .appendTo( 'head' );

        yourFunction();
    }
} );
Sign up to request clarification or add additional context in comments.

2 Comments

@Yi Jang: But are there any cross-domain solutions anyways? I am not even sure if that restriction has been lifted.
@Legend There are usually no way the restriction can be lifted - CORS exists, but that's only for recent browsers and only if the server explicitly allows this; JSONP isn't going to fly here simply because this isn't JSON.
0

Well. The tag should have a attribute named complete, that is set to true when it is loaded. You could test it every 50 milliseconds if you want or perhaps onload would work.

E.g.

var css = jQuery("<link>");
css.attr({
  rel:  "stylesheet",
  type: "text/css",
  href: "http://domain.com/chron/css/jquery.gritter.css"
})
.load(function() { /* callback */ });
$("head").append(css);

//As i have no idea whether the onload event
//works on link elements or not, try this instead:
setTimeout(function(){
    if(!css.complete)
    { setTimeout(arguments.callee, 50); }
    else
    { /* callback */ }
}, 50);

2 Comments

I don't think LINKs have a 'complete' property. At least not in all browsers.
@JAAulde: Yeah you might be right. And they probably don't have onload either :( so i guess the only solution left is to style a certain element, and then test if the element have gotten that style every 50 ms :(

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.