I was reading about console.log()
somewhere on Stackoverflow earlier today, and I remember reading that it causes IE to bug out. The user had said that all instances of it should be removed from the code before deployment or a javascript library could be used to omit it in IE.
My question is regarding this second option, how would one write such a library? Would it just be something that's run onload
that affects how the js is parsed from then forward? Like something that says if browser == IE, omit all instances of console.log()
... or would it be an extension to the console.log()
method that makes it self-aware of what browser it's being called in? I'm somewhat familiar with extending jQuery functions but have never seen this done with raw js. I'm inter开发者_运维问答ested in this because I feel like it would be a good way to achieve browser cross-compatiblity just in general, this isn't about console.log()
specifically.
One approach is to just make sure that console.log()
is always defined so you can always use it without worry. You can add this code to make sure that it is always defined.
This code will make it so that in IE (or in any other browser that doesn't have it), console.log()
will be defined and safely do nothing. When it does already exist, this code will do nothing leaving the previous definition of console.log()
in place and untouched.
if (!window.console) {
window.console = {};
}
if (!console.log) {
console.log = function() {};
}
There are a few different ways to go about testing for global properties that may or may not exist. You should try to be as defensive as possible, e.g.
var global = this;
if (!('console' in global)) {
global.console = {};
}
if (!('log' in global.console)) {
global.console.log = /* whatever */;
}
The in tests could perhaps use typeof instead. The idea is to not use an identifier that may not exist. Perhaps a little saner is:
// If console exists, declaring it will not hurt
// If it didn't exist, it does now
var console;
if (typeof console == 'undefined') {
console = {};
}
if (typeof console.log == 'undefined') {
console.log = /* whatever */;
}
精彩评论