Skip to content

Instantly share code, notes, and snippets.

@JoshuaKGoldberg
Last active December 28, 2016 19:13
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 JoshuaKGoldberg/c1077dd64aac756e0604beb2cd51840f to your computer and use it in GitHub Desktop.
Save JoshuaKGoldberg/c1077dd64aac756e0604beb2cd51840f to your computer and use it in GitHub Desktop.
NProgress and RequireJS with onResourceLoad and contexts._.defined
// 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