20
Jan/09
0

JavaScript: Load CSS files dynamically

JavaScript

I had problems to add some custom CSS file dynamically after the page has been rendered and sent to browser. In detail I have some HTML code (a template) in a dedicated file which is fetched via AJAX and should be added to a div-Container. The HTML may contain a <link> element which points to a custom css stylesheet.

It was no problem to to fetch the HTML code and append it to a div-Container by setting div.innerHTML = strCode;.

I tested my code in Firefox: No problem. After I finished coding I tested in Internet Explorer 6 and 7. Big Problem: The CSS file was requested by the browser but not recognized when rendering the HTML code. The CSS definitions were OK. I did not find out the exact reason but I got a workaround.

My JavaScript code knows the path to the HTML template file on the server. The CSS file is named like the template file excepting the file extension. So I am able to request the CSS file on the fly by manipulating DOM.

var sTemplateName = 'default';
 
// Load template css file
var oLink = document.createElement('link')
oLink.href = '/path/to/template/tmpl.'+sTemplateName+'.css';
oLink.rel = 'stylesheet';
oLink.type = 'text/css';
document.body.appendChild(oLink);
oLink = null;
 
// Request template code and proceed...

The CSS file is fetched by the JavaScript code now therefore I can remove the <link> tag without hesitation.

Filed under: Javascript
Comments (0) Trackbacks (0)

No comments yet.

No trackbacks yet.