i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i'm working with a single page application.
Well in an SPA the content is dynamic, right? so i didn't want to import all the style-sheets in the head section with the link tag. Can i somehow import style-sheets as-and-when i need them?
I mean, can i have a link in the body, such that whenever my SPA loads some dynamic content, a style sheet also gets loaded? Such that i dont have to load all the stylesheets even when the dynamic content is not loaded..
I stress again: Whenever the content loads, the styles load.
I know i can do it with the help of an inline style like this:
~PSEUDO CODE
<tagname style="somestyle"></tagname>
but can i have some dynamic file imports too? Can i have the link
tag in the body too? Even if it works, is it standard?
You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.
JavaScript
Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a
<head>
tag in your html.I just tried to give dynamic styling to my webpage. I used a button. On click of it, the CSS will get imported using a method in Javascript.
In my html, I have:
Then in Javascript, I have a method named changeStyle():
It worked perfectly.
You can add/remove/edit link tags in your head area with java script to add/remove stylesheet files.
Code example:
Add a stylesheet to the head:
To remove or edit a stylesheet you can give every stylesheet an id attribute and access it with this:
Or you can loop through all link tags in the head area and find the correct one but I suggest the solution with the ID ;)
Now you can change the href attribute:
Or you can remove the complete tag: