使用PerformanceObserver API获取和保存数据,以便进一步用于类-JS



我想获取PerformanceObserver提供的数据,并在我的应用程序中使用它。

在我的情况下,我想从只负责css文件的PerformanceObserver获取数据,并做一些事情(在这种情况下,只检查这些资源是否缓存(

下面是代码示例:

class Styles {
static getStyleResources() {
const styles = [];
const po = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if(entry.initiatorType === 'css') {
styles.push(entry);
return styles;
}
}
});
po.observe({ type: 'resource', buffered: true });
}
static isChached() {
return Styles.getStyleResources().forEach(item => item.transferSize ?
console.log("The data is cached") :
console.log("The data is not cached") 
)
}
}

我也尝试了不同的方法,但都没有成功。问题出在哪里?我走的路对吗?

PerformanceObserver异步工作,因此不能直接提取样式数组的值,因为它是一个连续流。我认为你需要抓住它,例如设置样式长度的限制。

const po = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if(entry.initiatorType === 'css') {
styles.push(entry);
return styles;
if (styles.length === 3) {
console.log(styles) // returns an accessible array with 3 entries
}
}
}
});

相关内容

最新更新