浏览器报找不到console对象,那我们就手动构造一个接口完全一致的console对象 置于window中。这里采用了空方法和空对象。如此一来即使在很old的浏览器中,含有console.xxxxx的代码依然不会报错,完美运行。
下面附上修复兼容代码,要置于置于第一句console.xxxx调用之前,否则没有意义。
复制代码 代码如下:
(function (){
//创建空console对象,避免JS报错
if(!window.console)
window.console = {};
var console = window.console;
var funcs = ["assert", "clear", "count", "debug", "dir", "dirxml",
"error", "exception", "group", "groupCollapsed", "groupEnd",
"info", "log", "markTimeline", "profile", "profileEnd",
"table", "time", "timeEnd", "timeStamp", "trace", "warn"];
for(var i=0,l=funcs.length;i<l;i++) {
var func = funcs[i];
if(!console[func])
console[func] = function(){};
}
if(!console.memory)
console.memory = {};
})();