在非WebKit浏览器中推迟JavaScript执行

时间:2012-07-11 06:34:19

标签: javascript internet-explorer firefox deferred-execution

我正在尝试使用Ryan Fioravanti的简洁技术推迟JavaScript执行。它在Google I / O的演示文稿的slide 27slide 28中进行了描述。

在WebKit浏览器中,它效果很好,提供了比将script标记放在页面底部或使用async属性更好的结果。

但是,它在Firefox或IE中不起作用。我可以在Firebug中看到脚本被插入到DOM中,但我也可以在Firebug中看到脚本本身从未执行过。

问题出现在<script src="..."></script>等外部脚本和<script>//inline code goes here</script>等内联脚本中。

有没有人让这种技术在非WebKit浏览器中工作?

以下是复制问题的相关源代码:

<script type="text/notJs">
    alert('This alert will show in Chrome and Safari thanks to the DOM manipulation below! But it does not show in Firefox or IE.');
</script>
<script>
    window.onload = function () {
        var scripts = document.getElementsByTagName('script');
        var scriptIndex = 0;
        for (var i = 0, len = scripts.length; i < len; i++) {
            var scriptEl = scripts[scriptIndex];
            if (scriptEl.type === 'text/notJs') {
                scriptEl.type = 'text/javascript';
                scriptEl.parentNode.removeChild(scriptEl);
                document.body.appendChild(scriptEl);
            } else {
                scriptIndex++;
            }
        }
    };
</script>

1 个答案:

答案 0 :(得分:0)

这里的代码似乎适用于Firefox,IE,Safari和Chrome。它适用于内联脚本和外部脚本。

<script>
    window.onload = function () {
        var scripts = document.getElementsByTagName('script'),
            scriptIndex = 0,
            newScript,
            scriptEl;
        for (var i = 0, len = scripts.length; i < len; i++) {
            scriptEl = scripts[scriptIndex];
            if (scriptEl.type === 'text/notJs') {
                scriptEl.parentNode.removeChild(scriptEl);
                newScript = document.createElement('script');
                newScript.type = "text/javascript";
                if (scriptEl.text) {
                    newScript.text = scriptEl.text;
                } else {
                    newScript.src = scriptEl.src;
                }
                document.body.appendChild(newScript);
            } else {
                scriptIndex++;
            }
        }
    };
</script>