Search code examples
javascripthtmlcssscriptlet

How to insert javascript function in css link tag


How can we call a javascript function inside some css link tag ?

For example:

<link rel="stylesheet" href="https://<%=getServerIP()%>/path/to/cssFiles/file1.css" type="text/css">

As we can see that, this scriplet works just fine. It calls scriptlet function. Grabs the IP. Access the css file.

I need to do the same thing with javascript function.

<link rel="stylesheet" href="https://'getServerIP()'/path/to/cssFiles/file1.css" type="text/css">

Why not the second way is not working ? Any work around ?

Thanks in advance. :)


Solution

  • There is no similar syntax in javascript for dropping variables into the html like you can in PHP. In order to dynamically load a CSS file in javascript, you would need to create a link element and append it to the head. Something like this:

    function loadCssFile(filename){
      var linkElement=document.createElement("link");
      linkElement.setAttribute("rel", "stylesheet");
      linkElement.setAttribute("type", "text/css");
      linkElement.setAttribute("href", filename);
      document.getElementsByTagName("head")[0].appendChild(linkElement);
    }
    
    var url = 'https://'+getServerIP()+'/path/to/cssFiles/file1.css';
    loadCssFile(url);