【问题标题】:Using PerformanceObserver API to get and save data for further usage with classes - JS使用 PerformanceObserver API 获取和保存数据以供进一步使用类 - JS
【发布时间】:2020-07-29 17:11:35
【问题描述】:

我想获取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") 
        )
    }
}

我也尝试了不同的方法,但没有任何效果。有什么问题,我的方法是否正确?

【问题讨论】:

    标签: javascript performance class monitoring


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      相关资源
      最近更新 更多