简体   繁体   中英

jQuery appending a CSS and running a function?

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?

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

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.

Eg

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

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