
Last week i discussed how to add Javascript Libraries dynamically in a Javascript file. In this post i will discuss how to add Cascading Style sheets pragmatically from a Javascript file.
The reason behind is same. Many a times developer references to external CSS files in their website/project like referring to bootstrap.css, bootstrap-responsive.css etc. When the list of external references increases and you have to use same libraries/files at different pages/projects, they can be included from within a single script. This way including a single script file includes all the other CSS files. A single line of code to refer the master script can add a reference to all these CSS libraries. To add all files add this function in a javascript file used in all the pages (say main.js):
function addStylesheet(filename) {
var tagPosition = document.getElementsByTagName('head')[0];
var scriptElement = document.createElement('link');
scriptElement.setAttribute('rel', 'stylesheet');
scriptElement.setAttribute('type','text/css');
scriptElement.setAttribute('href',filename);
tagPosition.appendChild(scriptElement);
}
This function works as follow:
1. Get the DOM element head and assign it to a variable tagPosition.
2. Create a DOM element script and assign it to a variable scriptElement .
3. Add an attribute ‘rel’ with value ‘stylesheet’ for the scriptElement.
4. Add an attribute ‘type’ with a value ‘text/css’ for the scriptElement.
5. Add an attribute ‘href’ with a value as a filename for the scriptElement. This file name is passed to our function.
6. Append the element scriptElement as a child element inside the tagPosition element. This will ensure stylesheet DOM element is included inside the head tags. To include script inside body tag, replace ‘head’ in line 1 of function by ‘body’
To call this function simply make a call like
addStylesheet('js/pdttrack/bootstrap.css');
addStylesheet('js/pdttrack/bootstrap-responsive.css');
Now, at any page you include main.js using the code
<script src="../main.js">
it will include both bootstrap.css and bootstrap-responsive.css.





















THANKS for the tutorial. keep up.
[…] Dynamically adding Cascading Style Sheets from within a Javascript file […]
Your means of describing the whole thing in this post is really
good, all can without difficulty understand it, Thanks
a lot.
You really make it seem so easy with your presentation but
I find this matter to be actually something that I think I would never understand.
It seems too complicated and very broad for me.
I’m looking forward for your next post, I will try to get the hang of it!