if (!/*@cc_on!@*/0) 判断的是什么?

2021/07/27

背景

项目开发中遇到一个问题,如何判断 iframe 是否加载完成?

解决方案非常简单,也很容易在网上找到答案:

var iframe = document.createElement("iframe");
iframe.src = "http://www.baidu.com/";

if (!/*@cc_on!@*/0) { //if not IE
    iframe.onload = function(){
        alert("框架加载完毕.");
    };
} else {
    iframe.onreadystatechange = function(){
        if (iframe.readyState == "complete"){
            alert("框架加载完毕.");
        }
    };
}

document.body.appendChild(iframe);

但本文的重点不是这个解决方案本身,重点是,请注意第四行

if (!/*@cc_on!@*/0) { //if not IE

这里对 IE 浏览器的判断条件是(!/*@cc_on!@*/0)

那么这个奇形怪状的条件到底是怎么来的?

答案

我在stackoverflow上找到了答案:

@cc_on Statement (JavaScript)

Activates conditional compilation support within comments in a script.

Caution

Conditional compilation is not supported in Internet Explorer 11 Standards mode and Windows Store apps. Conditional compilation is supported in Internet Explorer 10 Standards mode and in all earlier versions.

答案就在上面这段话里:

1.@cc_on语句用于激活脚本中注释的条件性编译支持。

2.Internet Explorer 11 标准模式和Windows Store应用程序不支持条件性编译 。在Internet Explorer 10标准模式和所有早期版本中,支持条件编译

这是人话?

确实乍一看很难理解,还好回答者给了我们一个例子:

/*@cc_on @*/
/*@
    document.write("JavaScript version: " + @_jscript_version + ".");
    document.write("<br />");
    @if (@_win32)
        document.write("Running on the 32-bit version of Windows.");
    @elif (@_win16)
        document.write("Running on the 16-bit version of Windows.");
    @else
        document.write("Running on a different operating system.");
    @end
@*/

观察上面这个例子,在/*@cc_on @*/语句的内部,是一段可执行的注释 ,所以以下语句

if(!/*@cc_on!@*/0)

在低于 IE 11 的浏览器中,会被视为:

if(!!0) // ==> FALSE

在非 【低于 IE 11 的浏览器】中,会被视为:

if(!/*...*/0) // ==> TRUE

因为/* ... */中的...部分会被当作注释来处理。

总结

if (!/*@cc_on!@*/0)通过一项只有IE11以下浏览器支持的可执行注释功能来判断当前浏览器版本,使用方法如下,

if (!/*@cc_on!@*/0){
    //不是IE11以下的浏览器
}else{
    //是IE11以下的浏览器
}