Javascript 性能:多个脚本块与单个更大的块
我在 IE8 上观察到奇怪的行为(在 FF 3.5 上没有看到)。 我创建了 2 个示例网页,其中仅包含一些 JS。 第1页:3个JS块(标签),其中包含非常小的内联JS。 Page2:与上面相同的 JS,但所有 3 个脚本合并在一个块中。
我使用 dynatrace 打开页面,观察到对于 page1,每个脚本解析/执行花费了大约 27-30 毫秒的时间。总时间约为 80 毫秒。 对于 Page2,合并后的 JS 花费了约 30 毫秒。 有人可以解释一下这背后的原因吗?将较小的 JS 块合并为一个更好吗?
PS:对于所有脚本,dynatrace 添加的检测时间可以忽略不计。 Firefox 3.5 没有表现出这种行为。此外,每个较小 JS 块的 FF 执行时间约为 1 毫秒,组合 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.
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: 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当浏览器遇到脚本块时,它必须在执行该块中的脚本时暂停渲染页面。
我不知道为什么 IE8 比 FF 的情况会如此明显。可能是上下文切换在 IE8 中成本特别高,或者 FF 可能会在幕后做一些工作来组合您的块,如果它确定可以(我只是在这里猜测)
脚本块也会阻止并行下载。如果您从多个主机名下载图像,则这可能会并行发生,除非您正在执行脚本块。
一般来说,我想说最好的做法是组合脚本块。就我个人而言,我建议您将它们移至单独的文件中。
顺便说一句,当您将指标移动到另一个文件时,会发生什么情况?
请参阅 Yahoo Developer 中的加快网站速度的最佳实践。
When a browser encounters a script block it has to pause rendering the page while it executes the script in that block.
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?
See Best Practices for Speeding Up Your Web Site at Yahoo Developer.