Calling Javascript Function To Include Stylesheet Fails
Here's the fail I'm having -- the 'sitePath' is a javascript variable at global file scope:
Solution 1:
The problem is that you can't use JavaScript to output the file path to the Stylesheet inside the href
attribute. When you use JavaScript for the href
of an anchor tag, the JavaScript function is only called when you click on the anchor tag. For a link element, it doesn't process the JavaScript at all.
If you want to dynamically load the CSS, you'll either need to use PHP to echo out the correct file path before the page is created or call a JavaScript function which will insert a link element into the DOM as @Pranav Ram suggested.
function loadStyleSheet( path, fn, scope ) {
var head = document.getElementsByTagName( 'head' )[0]
link = document.createElement( 'link' );
link.setAttribute( 'href', path );
link.setAttribute( 'rel', 'stylesheet' );
link.setAttribute( 'type', 'text/css' );
head.appendChild(link);
}
Post a Comment for "Calling Javascript Function To Include Stylesheet Fails"