我正在尝试 Ryan Fioravanti 的 clean-o 技术来推迟 JavaScript 执行。它在 slide 27 中有描述。和 slide 28他在 Google I/O 大会上的演讲。
在 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>
最佳答案
以下代码似乎适用于 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>
关于javascript - 在非 WebKit 浏览器中推迟 JavaScript 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11426875/