Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An implementation of $.getScript but for stylesheets. Call it $.getStylesheet
(function($) {
$.getStylesheet = function (href) {
var $d = $.Deferred();
var $link = $('<link/>', {
rel: 'stylesheet',
type: 'text/css',
href: href
}).appendTo('head');
$d.resolve($link);
return $d.promise();
};
})(jQuery);
@Necross220
Copy link

Necross220 commented Apr 25, 2021

Excelent thanks!

@lokpro
Copy link

lokpro commented Jul 30, 2021

It always callbacks done/then(), no matter the href is loaded or broken.

@lokpro
Copy link

lokpro commented Jul 30, 2021

And it callbacks when the $link element is appended. It is not like $.getScript that callbacks after the js file is loaded complete.

@lokpro
Copy link

lokpro commented Jul 30, 2021

I modified to make it works like $.getScript to fit my needs.

(function($) {
  $.getStylesheet = function (href) {
		return $.ajax({
			dataType: "text",
			url: href,
		}).done( function(text){
			$("<style>").html(text).appendTo("head");
		} );
  };
})(jQuery);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment