Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created February 3, 2016 21:05
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save james2doyle/9456c3e145f8d0afbe25 to your computer and use it in GitHub Desktop.
Save james2doyle/9456c3e145f8d0afbe25 to your computer and use it in GitHub Desktop.
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);
@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