无错误控制台日志记录

Avatar of Chris Coyier
Chris Coyier
var Fb = {}; //An empty object literal for holding the function
Fb.log = function(obj, consoleMethod) {
       if (window.console && window.console.firebug && window.console.firebug.replace(/^\s\s*/, '').replace(/\s\s*$/, '') !== '') {
               if (typeof consoleMethod === "string" && typeof console[consoleMethod] === "function") {
                       console[consoleMethod](obj);
               } else {
                       console.log(obj);
               }
       }
}

如果您在 JavaScript 代码中保留 console.log、console.info 等消息,并在 IE 等浏览器中打开页面,则可能会完全停止页面加载,并显示“console 未定义”错误,尤其是在用户使用非 IE8 浏览器时。

此代码片段将允许您保留代码中的日志记录消息(如果需要),并且页面将在 IE 或任何不支持控制台消息的浏览器中正常呈现。

用法

Fb.log("This will be logged");

Fb.log("This will be displayed in console as info", "info");

FB.log 函数接受两个参数,第一个参数是要在 Firebug 控制台中显示的“项目”,第二个参数是要用于日志记录的 Firebug 方法,例如 info、error 等。如果您省略第二个参数,则结果将等效于 console.log()

简单的只记录方式

function ltc(what) {
       try {
               console.log(what);
       }
       catch (e) {}
       finally {
               return;
       }
}
ltc("message");