简体   繁体   中英

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. :)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM