-
-
Save dark-reiser/93380a7c28b26aa99c16f304a180fc5c to your computer and use it in GitHub Desktop.
Dynamically add CSS link or rule to DOM w/ pure JavaScript
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
| // create a <link> with specific URL | |
| var addLink = function(url){ | |
| var link = document.createElement('link'); | |
| link.src = url; | |
| link.rel = 'stylesheet'; | |
| link.type = 'text/css'; // no need for HTML5 | |
| document.getElementsByTagName('head')[0].appendChild(link); // for IE6 | |
| }; | |
| // create a style that can append CSS rules to <head> | |
| var addCssRules = (function(){ | |
| var style = document.createElement('style'), styleTxt = []; | |
| style.type = 'text/css'; | |
| document.getElementsByTagName('head')[0].appendChild(style); | |
| return function(rules){ | |
| if(typeof rules === 'string'){ | |
| styleTxt.push(rules); | |
| }else if(rules instanceof Array){ | |
| for(var i = rules.length; i--;){ | |
| styleTxt.unshift(rules[i]); | |
| } | |
| }else{ | |
| return false; | |
| } | |
| if(typeof style.styleSheet !== "undefined"){ | |
| style.styleSheet.cssText += styleTxt.join(' '); | |
| }else{ | |
| style.appendChild(document.createTextNode(styleTxt.join(' '))); | |
| } | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment