首页 > 解决方案 > 使用 PerformanceObserver API 获取和保存数据以供进一步使用类 - JS

问题描述

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

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

这是代码示例:

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") 
        )
    }
}

我也尝试了不同的方法,但没有任何效果。有什么问题,我走对了吗?

标签: javascriptperformanceclassmonitoring

解决方案


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
                     }
                }
            }
        });

推荐阅读