"); css.a...">

Does jQuery add CSS and run a function?

I am trying to add a CSS file to the current HTML page as follows:

    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 loaded, I want to call a specific function. I thought I would just put the function call after the line $('head').append(css);, but not sure if this ensures that the css file will be loaded first before the function call. Can someone please tell me how to do this?

+3
source share
2 answers

How about getting through 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();
    }
} );
+4
source

Well. The tag must have an attribute named complete that is set to true. You can test it every 50 milliseconds if you want, or maybe onload will 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);
0
source

Source: https://habr.com/ru/post/1793331/


All Articles