问题描述
我在 IE8 上观察到了一个奇怪的行为(在 FF 3.5 上没有看到).我创建了 2 个示例网页,其中只有一些 JS.第 1 页:3 个 JS 块(标签),其中包含非常小的内联 JS.第2页:和上面一样的JS,但是所有3个脚本合并在一个块中.
I have observed a weird behavior on IE8(not seen on FF 3.5). I created 2 sample web pages with only some JS in it. Page1: 3 JS blocks ( tags) with very small inline JS in them. Page2: Same JS as above, but all 3 scripts combined in one block.
我使用 dynatrace 打开页面并观察到对于 page1,每个脚本的解析/执行时间约为 27-30 毫秒.总时间约为 80 毫秒.对于 Page2,合并后的 JS 耗时约 30 毫秒.有人可以解释这背后的原因吗?将较小的 JS 块合并为一个更好吗?
I opened the page using dynatrace and observed that for page1, each of the script took ~27-30ms time for parsing/execution. Total time is ~80ms. For Page2, the combined JS took ~30ms. Can someone please explain the reason behind this? Is it better to combine the smaller chunks of JS into one?
PS:对于所有脚本,dynatrace 添加的检测时间可以忽略不计.Firefox 3.5 没有表现出这种行为.此外,每个较小的 JS 块在 FF 上的执行时间约为 1 毫秒,而组合 JS 的执行时间约为 3 毫秒.
PS: For all the scripts, the instrumentation time added by dynatrace is negligible. Firefox 3.5 did not show this behavior. Also the execution time on FF was ~1ms for each of the smaller JS block and ~3ms for the combined JS.
推荐答案
当浏览器遇到脚本块时,它必须暂停渲染页面,同时执行该块中的脚本.
When a browser encounters a script block it has to pause rendering the page while it executes the script in that block.
我不确定为什么 IE8 比 FF 会如此明显.可能是 IE8 中的上下文切换成本特别高,或者 FF 可能会在幕后做一些工作来组合你的块,如果它确定可以的话(我只是在这里猜测)
I'm not sure why this would be so pronouced for IE8 over FF. It could be that the context switch is especially costly in IE8, or that FF may do some work behind the scenes to combine your blocks if it determines it can (I'm only guessing here)
脚本块也阻止并行下载.如果您从多个主机名下载图像,这可能会并行发生,除非您正在执行脚本块.
Script blocks also block parallel downloads. If you're downloading images from multiple hostnames, this can happen in parallel, unless you are executing a script block.
一般来说,我认为将脚本块组合起来是最佳做法.就个人而言,我建议您将它们移动到单独的文件中.
In general, I would say that it is best practice to combine your script blocks. Personally, I would recommend you move them into a separate file.
顺便说一下,当您将指标移到另一个文件时会发生什么情况?
Incidentally, what happens with your metrics when you do move it to another file?
请参阅 Yahoo Developer 的网站加速最佳实践.
See Best Practices for Speeding Up Your Web Site at Yahoo Developer.
这篇关于Javascript 性能:多个脚本块与单个更大的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!