[JavaScript] Load CSS Dynamically


To load (external) CSS file dynamically, insert the following LoadCSS function to your JavaScript code:

function LoadCSS(url) {
  var ext = document.createElement('link');
  ext.setAttribute("type", "text/css");
  ext.setAttribute("rel", "stylesheet");
  ext.setAttribute("href", url);
  document.getElementsByTagName("head")[0].appendChild(ext);
}

Example Usage of LoadCSS Function

Call the LoadCSS function by supplying path:

LoadCSS("/css/site.css");

or supplying URL:

LoadCSS("http://www.mysite.idv/css/site.css");

References:

[1][JavaScript] Load Favicon Dynamically
[2]Load External JavaScript or CSS file Dynamically
[3][GopherJS] Insert CSS Dynamically