Skip to content

Commit 31eb933

Browse files
prashantpalikheegoist
authored andcommitted
feat: Make use of requestIdleCallback if available (#6)
requestIdleCallback will start up the observation in the next available idle time of the browser, without getting in the way of anything important within the app.
1 parent 3b88be9 commit 31eb933

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/index.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import prefetch from './prefetch'
2-
import { canPrefetch, supportIntersectionObserver } from './utils'
2+
import { canPrefetch, supportIntersectionObserver, inBrowser } from './utils'
33

44
function installRouterPrefetch(Vue, { componentName = 'RouterLink' } = {}) {
55
const observer =
@@ -12,6 +12,20 @@ function installRouterPrefetch(Vue, { componentName = 'RouterLink' } = {}) {
1212
})
1313
})
1414

15+
const requestIdleCallback =
16+
(inBrowser && window.requestIdleCallback) ||
17+
function(cb) {
18+
const start = Date.now()
19+
return setTimeout(() => {
20+
cb({
21+
didTimeout: false,
22+
timeRemaining() {
23+
return Math.max(0, 50 - (Date.now() - start))
24+
}
25+
})
26+
}, 1)
27+
}
28+
1529
const RouterLink = Vue.component('RouterLink') || Vue.component('router-link')
1630

1731
if (process.env.NODE_ENV === 'development' && !RouterLink) {
@@ -34,9 +48,7 @@ function installRouterPrefetch(Vue, { componentName = 'RouterLink' } = {}) {
3448
},
3549
mounted() {
3650
if (this.prefetch && observer && canPrefetch) {
37-
setTimeout(() => {
38-
this.observe()
39-
}, 1000)
51+
requestIdleCallback(this.observe, { timeout: 1000 })
4052
}
4153
},
4254
beforeDestory() {

0 commit comments

Comments
 (0)