Skip to content

Instantly share code, notes, and snippets.

@AlonMiz
Last active February 24, 2023 13:01
Show Gist options
  • Save AlonMiz/737e18e273c75184b6cd7429c53dc9d6 to your computer and use it in GitHub Desktop.
Save AlonMiz/737e18e273c75184b6cd7429c53dc9d6 to your computer and use it in GitHub Desktop.
Lazy load vue route
// from this article https://medium.com/@alonmiz1234/retry-dynamic-imports-with-react-lazy-c7755a7d557a
export const retryImport = async (importer: () => Promise<any>) => {
try {
return await importer();
} catch (error: any) {
// retry 5 times with 1 second delay and backoff factor of 2 (2, 4, 8, 16, 32 seconds)
for (let i = 0; i < 5; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** i));
// this assumes that the error message that the browser exception will contain this specific text.
// if not, the url will not be able to parse and we'll get an error on that
const url = new URL(
error.message
.replace("Failed to fetch dynamically imported module: ", "")
.trim()
);
// add a timestamp to the url to force a reload the module (and not use the cached version - cache busting)
url.searchParams.set("t", `${+new Date()}`);
try {
return await import(url.href);
} catch (e) {
console.log("retrying import");
}
}
throw error;
}
};
// https://router.vuejs.org/guide/advanced/lazy-loading.html
const UserDetails = () => retryImport(() => import("./views/UserDetails.vue"));
const router = createRouter({
// ...
routes: [{ path: "/users/:id", component: UserDetails }],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment