I am working on a site where we still need to support IE8, and we are trying to include the Twitter share button widget.
In IE8 we are seeing the 'Expected Identifier' error. This seems a common problem, and posts such as the following explain it fully and well:
Basically Twitter have stopped supporting IE8 (I wish I could do the same ;) ) - but more importantly, the error is caused by the fact that the Twitter widgets.js file appears to be referencing a property named delete
via dot notation (that's what the first SO post I referenced above suggests anyway)
Based on the 2 above SO posts, there are 2 workarounds - either take a copy of widgets.js and change the property name from delete
to something else; or use a conditional comment to prevent it being loaded in IE8
I don't like the idea of taking a copy (and having to maintain it forever!) of the widgets.js file, so I'm looking at preventing it being loaded in IE8. But I don't want to use conditional comments; I want to use feature detection.
So I'm trying to write the following which I can use to decide whether to call the Twitter async library loading code or not:
NTJSLibrary.prototype.hostSupportsDeleteKeywordAsPropertyName = function hostSupportsDeleteKeywordAsPropertyName() {
var testObj = {"delete":true};
try {
return testObj.delete;
}
catch (e) {
// Host does not support referencing a property named 'delete' and has thrown an exception
return false;
}
};
Unfortunately it doesn't work because IE8 throws a SCRIPT1010
error, which is a compilation/interpretation error, rather than a runtime error. IE doesn't throw an exception because it doesn't run!
Does anyone know how I can write a feature detection function to detect whether referencing the reserved word delete
via dot notation will cause a compilation/interpretation error?
The reason why you can't just test it with a try-catch statement is that syntax errors are "early errors" in JavaScript, which means that the error is thrown immediately without even attempting to execute the code. (See What types of errors are caught by try-catch statements in Javascript? for a more detailed explanation.)
To work around this, we have to use some way to dynamically create code, which will avoid this issue. In JavaScript, you can do so using new Function
or eval
(in this case, using eval
is acceptable as we are not executing user-defined code and there is no real way around using it).
An example of a test could be something like this:
function testReservedWords() {
try {
new Function('a.delete');
return true;
} catch (e) {
return false;
}
}