0

Here's the fail I'm having -- the 'sitePath' is a javascript variable at global file scope:

  <link rel="stylesheet" type="text/css"     
          href="javascript:getJval('sitePath')/rb_UI_styles.css" />

Here is getJval():

  function getJval(theVal)
  {
      return theVal;
  }

Originally I tried this but it didn't work:

  <link rel="stylesheet" type="text/css"     
          href="javascript:sitePath/rb_UI_styles.css" />     

I read a bunch of SO posts, including this one, many of these posts I've read have an 'href' that gets set by using the

     href="javascript:someFunc(someparam)" 

syntax.

However, this syntax to call a javascript function to set an 'href' is not working for me in the href for pulling in a stylesheet:

  <link rel="stylesheet" type="text/css"     
          href="javascript:getJval('sitePath')/rb_UI_styles.css" />

Can't figure out why. I know the stylesheet can be pulled in because if I replace the above with the actual URL to the CSS file, the styles appear successfully on the web page.

Does this javascript:function() syntax not work to set an href in a stylesheet link, for some reason?

1

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.