在Firefox

时间:2016-03-16 11:41:00

标签: javascript firefox dom

我一直在做一些实验来理解DOMContentLoaded event。 在进行实验时,我发现了Firefox和Chrome之间的一个有趣的区别(在Ubuntu上)。

我有这个HTML文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script>
        console.log('script is running');

        document.addEventListener( "DOMContentLoaded", function() {
            console.log('DOM content loaded');
        }, false );

        var x = 0;
        for(var i = 0; i < 900000000; i++) {
            x++;
        }

        setTimeout(function() {
            console.log('timeout callback is running');
        }, 10);

        console.log('script finished');
    </script>
</head>
<body>
    <div>div content</div>
</body>
</html>

Firefox控制台中的输出:

script is running
script finished
timeout callback is running
DOM content loaded

在Chrome控制台中,我得到:

script is running
script finished
DOM content loaded
timeout callback is running

如果我将超时时间延长到100毫秒,我也会在Firefox中获得Chrome的输出。

所以,似乎在Firefox上超时回调&#34;劫持&#34;下一帧,即使DOMContentLoaded被解雇了? 或者它可能只在回调返回后触发?

[编辑]

我添加了动态加载的脚本:

console.log('script is running');

document.addEventListener( "DOMContentLoaded", function() {
    console.log('DOM content loaded');
}, false );

setTimeout(function() {
    console.log('timeout callback is running');
}, 1);

var script = document.createElement('script');
script.src = 'dynamic.js';
document.head.appendChild(script);

var x = 0;
for(var i = 0; i < 1000000000; i++) {
    x++;
}

console.log('script finished');

dynamic.js:

(function() {
    console.log('dynamic script is running');

    var x = 0;
    for(var i = 0; i < 2000000000; i++) {
        x++;
    }

    console.log('dynamic script finished');
})();

现在,Firefox控制台输出是:

script is running
file:///foo/bar/dynamic.js
script finished
dynamic script is running
dynamic script finished
timeout callback is running
DOM content loaded

所以Firefox甚至等待动态加载的脚本在DOMContentLoaded回调运行之前返回?

1 个答案:

答案 0 :(得分:1)

两者都是异步的,并且它们不是因果关系。这是预期的race condition - 有时DOM快于10毫秒,有时不是。

当然结果 - 如果它们是可重现的 - 可能表明Chrome比Firefox更快,或者Firefox只是优先考虑DOM事件的超时。没关系。没有一个实现是“错误的”。