Last active
December 28, 2016 19:13
-
-
Save JoshuaKGoldberg/c1077dd64aac756e0604beb2cd51840f to your computer and use it in GitHub Desktop.
NProgress and RequireJS with onResourceLoad and contexts._.defined
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Start showing a progress bar | |
NProgress.start(); | |
// Remember how many resources have been requested | |
let completed = 0; | |
let oldPercentage = 0; | |
// Delay calculations so that if the first of a few resources has many dependencies, | |
// we don't immediately jump far in the progress bar before starting their loads | |
requirejs.onResourceLoad = context => { | |
setTimeout( | |
() => { | |
// Don't run this logic if NProgress has finished since it was scheduled | |
if (!NProgress.status) { | |
return; | |
} | |
// Tell the user whenever we make progress (only on increased percentages) | |
const newPercentage = (completed += 1) / Object.keys(context.defined).length; | |
if (newPercentage > oldPercentage) { | |
NProgress.set(newPercentage); | |
oldPercentage = newPercentage; | |
} | |
}, | |
100); | |
}; | |
// Send a network request, and when it's done, hide the bar | |
sendNetworkRequest().then(() => { | |
NProgress.stop(); | |
delete requirejs.onResourceLoad; | |
doOtherWork(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment