Adding CSS To Header

I am currently working on a website that sources in a header and footer — not an uncommon thing to do as this ensures a consistent look across the site. The lead-in code starts head, closes head, starts body, and defines the common page elements (nav bar, etc). The footer then defines some more common page elements and closes body. This approach creates a problem when you want to add CSS. Now you could use style tags within the HTML, but I would rather not have the same style definition twenty times. Yeah, I’d make a single variable out of it and print the style-definition-variable twenty times … but I’d rather have my CSS sourced in from a style-sheet file.

Since I’m already using jQuery to dynamically append elements — add table rows as data is pulled back from the server — I wondered if you could append something to the header. Yes, you can!

/**
* This function appends a CSS file to the document head
*
* @param {string} strFileName Path to CSS file
* @return n/a
*
* @example
*
* loadCSSStylesheetToHead('/path/to/file.css')
*/
function loadCSSStylesheetToHead(strFileName){
var file = document.createElement("link");
file.setAttribute("rel", "stylesheet");
file.setAttribute("type", "text/css");
file.setAttribute("href", strFileName);
document.head.appendChild(file);
}

This allows me to after-the-fact add css from a style-sheet file into the document head.

Leave a Reply

Your email address will not be published. Required fields are marked *