Friday, June 16, 2017

Load css based on browser identification

Loading a CSS file based on browser is not a good idea, However I will share the below code to identify browser.

Let it to do by javascript by onload method.

<script type="text/javascript">
 //Short code with ternary
 window.onload = function() {

  var link = document.createElement('link');
  link.rel = "stylesheet";
  link.type = "text/css";

  //Browser Detection
  link.href = (navigator.userAgent.indexOf("Chrome") != -1) ?link.href = "./css/grid.css";
    : (!(window.ActiveXObject) && "ActiveXObject" in window) ? link.href = "./css/iegrid.css";
      : "";
  document.querySelector("head").appendChild(link);
 }
</script>

Some people may document.write method, but It will not work in all case. Since document.write will swipes out the screen. So based on your task situation you should use this.