Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent redundant patching of History API methods #18

Merged
merged 2 commits into from
Feb 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,22 @@ const HolyLoader = ({
} catch (error) {}
};

/**
* Flag to prevent redundant patching of History API methods.
* This is essential to avoid pushState & replaceState increasingly nesting
* withing patched versions of itself
*/
let isHistoryPatched = false;

/**
* Enhances browser history methods (pushState and replaceState) to ensure that the
* progress indicator is appropriately halted when navigating through single-page applications
*/
const stopProgressOnHistoryUpdate = (): void => {
if (isHistoryPatched) {
return;
}

const originalPushState = history.pushState.bind(history);
history.pushState = (...args) => {
stopProgress();
Expand All @@ -145,6 +156,8 @@ const HolyLoader = ({
stopProgress();
originalReplaceState(...args);
};

isHistoryPatched = true;
};

/**
Expand Down Expand Up @@ -173,7 +186,6 @@ const HolyLoader = ({
}

startProgress();
stopProgressOnHistoryUpdate();
} catch (error) {
stopProgress();
}
Expand All @@ -192,6 +204,7 @@ const HolyLoader = ({
});

document.addEventListener('click', handleClick);
stopProgressOnHistoryUpdate();
} catch (error) {}

return () => {
Expand Down
Loading