user877329 user877329 - 1 month ago 5x
HTML Question

Hide scripts from semi-old browsers

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
    //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( However, this may be overkill in some situations.