性能监控与优化
这是一个用于监控和优化网页性能的网站。通过提供一些实用的方法和工具,帮助开发者更好地了解网页在运行过程中的表现,从而找到潜在的性能瓶颈并进行优化。
性能标记(mark)
使用window.performance.mark
方法可以为代码执行的关键点添加一个性能标记。这些标记可以在后续使用window.performance.getEntriesByName()
方法获取。例如:
window.performance.mark('start');
// ... 需要计时的代码 ...
window.performance.mark('end');
这样就可以得到从开始到结束的执行时间,便于分析和优化。
性能测量(measure)
window.performance.measure
方法可以用于对指定区域的性能进行测量。它接收一个名称作为参数,并返回一个包含以下属性的对象:
name
: 测量的名称。duration
: 测量所花费的时间,以毫秒为单位。entryType
: 测量条目类型,如”navigation”、”resource”等。- 其他相关属性和方法:更多关于
performance.measure
的信息请参考MDN文档。
我们可以使用window.performance.measure
来测量页面加载时间:
var measureElement = document.getElementById('measure');
window.performance.measure('measure', 'start', 'load', measureElement);
性能当前时间(now)
如果window.performance.now
方法不存在,可以通过创建一个自定义的函数来实现。在这个例子中,我们首先尝试从performance.timing
对象的navigationStart
属性获取当前时间偏移量,如果不存在则使用默认值(即当前时间减去Date.now()
)。
if ("now" in window.performance === false) {
var nowOffset = Date.now();
if (performance.timing && performance.timing.navigationStart) {
nowOffset = performance.timing.navigationStart;
}
window.performance.now = function now() { return Date.now() - nowOffset; };
}