Tutorial :How can I place HTML in a JavaScript string and have it validate?



Question:

I want to show different css files depending on browser that user is using. I want to do this on JS and on client side. I am using code like this.

 <script language="javascript" type="text/javascript">   if ((navigator.userAgent.indexOf("MSIE")) >= "0"){      document.write("<link rel=\"stylesheet\" href=\"css/common.IE.css\" type=\"text/css\"    }   if ((navigator.userAgent.indexOf("Chrom")) >= "0"){      document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\" type=\"text/css\" />");   }  

*The only problem that I this code is not valid. How I can solve the problem. If I check this document with w3 checker. it will show now: Line 22, Column 90: document type does not allow element "link" here*****

…nt.write("<link rel='stylesheet' href='css/common.IE.css' type='text/css' />");  

Line 25, Column 35: an attribute value must be a literal unless it contains only name characters

document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\"…  


Solution:1

break it up in sub-strings so that it does not get detected ..

document.write("<l" + "ink ...  

or add comments like this

<script type="text/javascript">  //<!--    if ((navigator.userAgent.indexOf("MSIE")) >= "0"){      document.write("<link rel=\"stylesheet\" href=\"css/common.IE.css\" type=\"text/css\"    }   if ((navigator.userAgent.indexOf("Chrom")) >= "0"){      document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\" type=\"text/css\" />");   }      //-->  </script>  


Solution:2

Wrap that block in CDATA tags.

So it looks like like...

<script language="javascript" type="text/javascript">  <![CDATA[   if ((navigator.userAgent.indexOf("MSIE")) >= "0"){      document.write("<link rel=\"stylesheet\" href=\"css/common.IE.css\" type=\"text/css\"    }   if ((navigator.userAgent.indexOf("Chrom")) >= "0"){      document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\" type=\"text/css\" />");   }  ]]>  <script>  


Solution:3

Bad idea. Can you tell us your real issues which are causing you to serve different stylesheets to different browsers?

You should strive to serve all browsers with one stylesheet, and maybe an additional to IE with CondComs ( sounds like condoms ).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »