In my Angular application I want to load the css files in a modular way - each module has it's own css file. This way I can add, remove or move modules easily.
The best way I found so far to do it is by creating a service:
angular.module('cssLoadingService', []).factory("CssLoadingService", function () {
return {
loadCss: function (url) {
if (document.createStyleSheet) { //IE
document.createStyleSheet(url);
} else {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
}
};
});
Each controller loads it's template css. Although I inject the path (by another service), still it feels like I'm breaking the seperation between the logic and the view.
It there any other elegant way (that doesn't includes packing the css files into one huge file)?
If your target is HTML5 browser, and assuming that you have a view per module, you can use scoped stylesheets in your views to accomplish this. If you wish to use a css file, you can use @import
syntax to load the css file into the <style>
tag. Here is a HTML of a view:
<div>
<style scoped>@import url('main.css')</style>
<h1>This is Main and should be Gray</h1>
</div>
Check out this plunker. It worked for me in the latest version of Chrome (27.x) and Firefox (21.x) under Mac OS X.
Please note that many recommend against the use @import
for performance reasons. In fact, you can see that there is slight delay between loading of the page and style being applied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With