CSS-hack – Adding css in the body of a website

We have different ways to load a CSS File.

1 – HTML – The conventional way to load external CSS files on a page is:

<head>
   <link rel="stylesheet" type="text/css" href="file.css" />
</head>

2 – CSS – Using the tag import from your CSS file

@import  url("another_file.css");

3 – JavaScript – Using only JavaScript to do it, you should create a Javascript function:

<script type="text/javascript">

   function loadCSS(filename){ 
      var file = document.createElement("link");
      file.setAttribute("rel", "stylesheet");
      file.setAttribute("type", "text/css");
      file.setAttribute("href", filename);
      document.head.appendChild(file);
   }

   //just call a function to load your CSS
   //this path should be relative your HTML location
   loadCSS("path_to_css/file.css");
</script>

4 – JavaScript – Either you can add dynamic definitions such as:

<script type="text/javascript">

   var sheet = (function() {
      var style = document.createElement("style");
      style.appendChild(document.createTextNode(""));
      document.head.appendChild(style);
      return style.sheet;
   })();

   sheet.insertRule("span { visibility: hidden }", 1);
</script>

Leave a Comment