Auf Deutsch lesen
In a Single-Page Application the stylesheets will only be loaded once. But different parts of the application might still need a distinct look and feel. Here I will present a solution I used to load different CSS Frameworks when bootstrapping the application.
As an example we want to use three different CSS Frameworks: Bootstrap, Materialize and Pure. The simplest solution would be to load all of them in the header, link so:
In this example the last rule wins and will overwrite all the previous ones. This messes up the distinct look of each framework.
The idea is to remove all stylesheets on load and dynamically add the ones which are required. The following sample will demonstrates how it works.
To achieve this I used a service that is used in one of the route's resolve functions.
All the service needs to know is the name of the stylesheet and it's path. The service then will add a new link node to the
<head> of the DOM which represents the new stylesheet. This will immediately rerender the page using the new stylesheet.
However, this does not solve the problem of using elements of different frameworks on the same page.
This can only be achieved by prefixing the stylesheets with a class and then wrapping the elements in the code with said class. To do this we will use prefix-css, which can be installed like so:
npm install -g prefix-css
After that one simple command is enough:
$ prefix-css .bootstrap bootstrap.min.css > bootstrap.prefixed.min.css
Prefixing integrated into the example above will look like this:
Keep in mind that a non-prefixed framework will affect the prefixed elements. To avoid that only use prefixed stylesheets, this can however make layouting very complicated.
The idea and some of the code is based on this post.
There also exists a more elaborate service called angular-css ready to be integrated into an application.
21. June 2015