问题描述:
项目要求兼容 ie9,开发的时候一直使用win10自带的ie11中的控制台降版本到ie9去开发,开发的时候一直显示都没问题。今天测试的时候,测试小姐姐用真正的ie9去打开发现如下问题:
(1)打开页面后部分功能无法实现;
(2)按F12打开控制台后,再刷新页面就能恢复正常;
(3)使用其他的浏览器比如chrome后就没有问题;
原因分析:
IE8 / 9 上在不打开调试工具的情况下window 上是没有 console 这个属性的!在打开调试工具的时候会给 window 再挂载上 console 属性,所以需要兼容 console 。
解决方法:使用兼容写法
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// 注:经验证在IE7/8/9下有效。
虽然IE11能在控制台中进行降版本模拟低版本的IE,但这种模拟并不完整,总有一些意想不到的小问题出现。如果需要开发兼容低版本浏览器的代码,最好使用真正的低版本IE。(可以在虚拟机上安装win7系统,win7自带ie8)
附参考链接: