Skip to content

Instantly share code, notes, and snippets.

@cvazac
Last active September 14, 2017 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvazac/22194645f411a68a50c39c88f05faf2d to your computer and use it in GitHub Desktop.
Save cvazac/22194645f411a68a50c39c88f05faf2d to your computer and use it in GitHub Desktop.
!(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