Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
!(function() {
const nativePO = window.PerformanceObserver
const interfaces = {
resource: 'PerformanceResourceTiming',
longtask: 'PerformanceLongTaskTiming',
// etc.
}
const polyfills = {
longtask: LongTaskPolyFill
// etc.
}
window.PerformanceObserver = (callback) => {
let po, filteredEntryTypes, registeredPolyFills = []
const observe = function(options) {
filteredEntryTypes = (options.entryTypes || []).filter((entryType) => {
const hasNativeSupport = typeof window[interfaces[entryType]] !== 'undefined'
if (!hasNativeSupport) {
const polyfill = polyfills[entryType]
polyfill && registeredPolyFills.push(polyfill.start(callback))
}
return hasNativeSupport
})
if (filteredEntryTypes.length) {
po = new nativePO((entries, observer) => {
callback(entries, this)
})
po.observe({
...options,
entryTypes: filteredEntryTypes,
})
}
}
const disconnect = () => {
if (po) {
po.disconnect()
po = undefined
}
registeredPolyFills.forEach(p => p.stop())
registeredPolyFills = []
}
return {
observe,
disconnect
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment