1

So I can still use HTML comments to hide javascript from a browser that does not know the script tag, fine.

But what is the most clean way of stopping semi-old browsers for trying to execute code they do not understand, resulting in hordes of script errors. I guess this is a larger problem, since new features are always added. Also, semi-old browsers are more likely to be in use.

vsync
  • 118,978
  • 58
  • 307
  • 400
user877329
  • 6,717
  • 8
  • 46
  • 88
  • possible duplicate of [Hide Javascript Code to Older Browser](http://stackoverflow.com/questions/11354453/hide-javascript-code-to-older-browser) – plalx Mar 09 '14 at 14:24
  • @plalx: No, I mean hide the script from browser who thinks, he understand, and spits out syntax errors as well as undefined errors. That is why i say semi-old. It supports old version of JavaScript. – user877329 Mar 09 '14 at 14:29
  • 2
    The best way to do this is feature detection. If it's a new syntax, you can usually detect support with a `try..catch`. – Paul S. Mar 09 '14 at 14:39

2 Answers2

0

Can you provide the brower that you want to check. For IE you can check the browser version using Conditional comment . i.e,

<!--[if gte IE 7]>
<script>
  alert("Congratulations! You are running Internet Explorer 7 or a later version of Internet Explorer.");
</script>
<p>Thank you for closing the message box.</p>
<![endif]-->

You can use the navigator to check the version of browser and run the desired function.

arivu86
  • 81
  • 2
  • 2
  • 12
  • It's upto your requirement. But we can possibly write the poly-fills like [this](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills) – arivu86 Mar 09 '14 at 14:38
  • this only applies to explorer browsers and not ones of other vendors. you should consider deleting your answer as it is not a good one at all and might mislead readers. – vsync Sep 15 '16 at 11:41
0

The answer is feature detection. The basic premise is that you check that any features you are going to use exist before you execute the code. As a very simple example lets look at the alert function. Your code would look like follows

if (alert){
    //do something
}
else{
    //no alert avaliable
} 

Of course alert is something that you would be unlikely to use in production, and therefore something unlikely to be tested for. However, this basic idea can be used for most situations.

For a simple implementation that works with every feature I would suggest you look at modernizer(modernizr.com). However, this may be overkill in some situations.

Braders
  • 447
  • 2
  • 11