Why injectCSS? Why make it? What is it solving?
- The primary goal was to create an easy way to include multi-line (lots) of CSS using Javascript.
- Can reduce number of files in a JS plugin or project (My goal was one).
- A test run at jsperf.com shows that injecting CSS rules for a vast number of elements is very fast.
Example Usage
With RequireJS
This file contains 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
require(['injectCSS'], function(injectCSS) { | |
injectCSS(function(){/* | |
.case1 { | |
border: 3px solid #0f0; | |
} | |
*/}); | |
injectCSS('.case2 { border: 3px solid #00f; } '); | |
}); |
With no dependencies
This file contains 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
<!DOCTYPE html> | |
<head> | |
<script src="injectCSS.js"></script> | |
</head> | |
<body> | |
<div class="test case1">test case 1</div> | |
<div class="test case2">test case 2</div> | |
<script> | |
(function(){ | |
injectCSS(function(){/* | |
.case1 { | |
border: 3px solid #0f0; | |
} | |
*/}); | |
injectCSS('.case2 { border: 3px solid #00f; } '); | |
})(); | |
</script> | |
</body> | |
</html> |
Compatability
Tested successfully on:
- Chrome (+mobile)
- Firefox
- Safari (+mobile)
- IE 10+
Download
The code is on GitHub. Download, use and modify as you please.
No comments:
Post a Comment