Javascript性能:多个脚本块与单个更大的块 [英] Javascript Performance: Multiple script blocks Vs single bigger block

查看:61
本文介绍了Javascript性能:多个脚本块与单个更大的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IE8上观察到一种奇怪的行为(在FF 3.5上没有看到)。
我创建了2个示例网页,其中只有一些JS。
Page1:3 JS块(标签)中包含非常小的内联JS。
Page2:与上面相同的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-30ms的时间进行解析/执行。总时间约为80毫秒。
对于Page2,组合JS需要大约30ms。
有人可以解释一下这背后的原因吗?将较小的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的执行时间约为1ms,组合JS的执行时间约为3ms。

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?

参见雅虎开发者加速网站的最佳实践

这篇关于Javascript性能:多个脚本块与单个更大的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆