Something works in IE, but only when I enable the developer tools..
The reason is quite simple, but difficult to figure out:
IE doesn't support console.log().
If you have any console prints in your code, these would throw exceptions (hence breaking the javascript after it) if the page was loaded when the developer tools were closed.
But if you have developer tools enabled, then all of a sudden these console.log() functions are allowed, causing the rest of your javascript to work just fine.
to fix this, wrap your prints in an if statement:
if (console) {
console.log('...');
}
Written by Jan Van Lysebettens
Related protips
3 Responses
Great tip, I remember this one causing me all kinds of havoc. You could also declare the console object if it doesn't exist. Then set log to a function that does nothing. Just in case... :)
It is easier to have a fallback for browsers that don't support console.log by adding following code:
var alertFallback = true;
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
if (alertFallback) {
console.log = function(msg) {
alert(msg);
};
} else {
console.log = function() {};
}
}
This keeps your code DRY and much more managable.
you could simply do window.console && console.log(foo);
and achieve the same results without any if statements.