Skip to content

Instantly share code, notes, and snippets.

@damon-kreft
Last active June 12, 2017 11:42
Show Gist options
  • Save damon-kreft/21c9cb22ba1e35dc476aa449b87aec81 to your computer and use it in GitHub Desktop.
Save damon-kreft/21c9cb22ba1e35dc476aa449b87aec81 to your computer and use it in GitHub Desktop.
import { addStateListeners } from './storeObserver'
import { addPostDispatchListeners } from './listenerMiddleware'
let startTime = null
let dataLoaded = true
let pageRendered = false
const start = (time) => {
startTime = time
dataLoaded = true
pageRendered = false
}
// This watches for page changes
addStateListeners(
(oldState, newState, store) => {
const oldPath = oldState && oldState.routing.location.pathname
const newPath = newState && newState.routing.location.pathname
// When there is no oldState, this is the initial app load so we know to use the browser timer
if (!oldState) {
// look at the browser's start timer
start(browserStartTimer)
}
// Then check for a all subsequent page changes
else if (oldPath !== newPath) {
start(Date.now())
}
}
)
// This action listener to be fired on the router wrapper's componentWillUpdate()
addPostDispatchListeners('PAGE_RENDERING', () => {
pageRendered = false
})
// This action listener should be fired on the router wrapper's componentDidMount/Update()
addPostDispatchListeners('PAGE_RENDERED', (action, store) => {
pageRendered = true
validatePageLoad(store)
})
// This action listener to be fired by superagent middleware keeping accurate tracking of all data calls
addPostDispatchListeners('PAGE_DATA_LOADING', () => {
dataLoaded = false
})
// This action listener to be fired by superagent middleware keeping accurate tracking of all data calls
addPostDispatchListeners('PAGE_DATA_LOADED', (action, store) => {
dataLoaded = true
validatePageLoad(store)
})
const validatePageLoad = (store, startTime) => {
if (startTime && dataLoaded && pageRendered) {
const loadTime = Date.now() - startTime
store.dispatch({ type: 'PAGE_LOADED', loadTime })
startTime = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment