Last active
September 26, 2015 12:47
-
-
Save ChrisMBarr/1099622 to your computer and use it in GitHub Desktop.
Add a CSS stylesheet to the head of a document
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.extend({ | |
includeCss: function(cssLink, isPrint, callbackFn) { | |
var $head = $("head"); | |
//Make sure it's a valid string and not already included in the head | |
if (typeof cssLink === "string" && cssLink.length > 1 && $head.find("link[href='" + cssLink + "']").length <= 0) { | |
//Create a new link element | |
var $newLinkTag; | |
var mediaType = (isPrint) ? 'print' : 'all'; | |
//Needed for IE8 and lower | |
if (typeof document.createStyleSheet !== "undefined") { | |
document.createStyleSheet(cssLink); | |
$newLinkTag = $head.find("link[href='" + cssLink + "']"); | |
$newLinkTag.attr({ | |
"media": mediaType, | |
"data-dynamic": "true" | |
}); | |
} else { | |
//Add the CSS file to the head | |
$newLinkTag = $("<link rel='stylesheet' type='text/css' data-dynamic='true' media='" + mediaType + "' href='" + cssLink + "' />"); | |
$head.append($newLinkTag); | |
} | |
//Convert the 2nd param to the callback if it's a function and the 3rd is undefined | |
if (typeof callbackFn === "undefined" && $.isFunction(isPrint)) callbackFn = isPrint; | |
//Run the callback | |
if ($.isFunction(callbackFn)) callbackFn($newLinkTag); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Simple:
$.includeCss('link/to/file.css');
will add
<link href="link/to/file.css" rel="stylesheet" media="all" type="text/css">
to the document head.Make it a print stylesheet:
$.includeCss('link/to/file.css',true);
will add
<link href="link/to/file.css" rel="stylesheet" media="print" type="text/css">
to the document head.Add a callback function:
$.includeCss('link/to/file.css',true,function(css){ console.log("I'm Done!", css); });
or, skip the 2nd param:
$.includeCss('link/to/file.css',function(css){ console.log("I'm Done!", css); });
the paramaeter passed to the callback function will return the newly created link element in the head - just in case that's needed!