質問

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.

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top