Matt said:
This is often said, but this is a good example - if a person wants to use
===, and doesn't specify the language="Javasscript1.2" then how can they
make sure older browsers don't execute the code block?
1.2 doesn't help as === is 1.3 but maybe that is a typo.
The typical answer is "test for features" but you can't test for new
operators like you can for properties of objects. If you use try/catch, then
that breaks in older browsers.
How can a developer use === and not break older browsers?
One way I see is using several script blocks and probably external
script files with different versions (e.g. one using === and one using
==) in the following way:
<script type="text/javascript">
var idTest = false;
</script>
<script type="text/javascript">
idTest = 1 === 1;
</script>
<script type="text/javascript">
if (idTest) {
var src = 'fileId.js';
}
else {
var src = 'file.js';
}
document.write('<script type="text/javascript" src="' + src +
'"><\/script>');
</script>
With older browsers the second script block should yield a syntax error
and therefore in the third script block the variable idTest is false so
you can write out a reference to a file.
A similar scheme should work for try/catch e.g.
<html>
<head>
<title>Checking for try/catch</title>
<script type="text/javascript">
var tcTest = false;
</script>
<script type="text/javascript">
try {
tcTest = true;
}
catch (e) {
}
</script>
<script type="text/javascript">
if (tcTest) {
var src = 'test20040416tc.js';
}
else {
var src = 'test20040416.js';
}
document.write('<script type="text/javascript" src="' + src +
'"><\/script>');
</script>
</head>
<body>
</body>
</html>
with test20040416tc.js being for test cases just
alert('Could use try/catch here.');
and the other file then
alert('Can\'t use try/catch here.');
That way if you try the test case with Netscape 4 which doesn't support
try/catch no error is generated and you can load a script file which
doesn't use try/catch.
But as said I think you can safely ignore browsers not supporting ===,
you can't forever try to make sure your script doesn't break with
antiquated browsers.
As for try/catch if you still think you have to deal with Netscape 4
users then you have the choice to avoid try/catch totally or use an
approach as outlined above. There are also other ways to use try/catch
in certain browsers safely (e.g. IE with conditional comments, Netscape
6/7 respectively Mozilla with <script type="text/javascript;
version=1.5">) if you are only scripting features for those browser like
XMLHttpRequest.