5

[JavaScript] Load CSS Dynamically

 2 years ago
source link: https://siongui.github.io/2012/10/10/javascript-load-css-dynamically/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK