I would like to listen to path changes in a SPA which is not maintained by me.
I found one solution here: https://stackoverflow.com/a/44819548/7042552
But still, it seems kind of "hacky" to me - but still my implementation is like this:
let url = window.location.href;
['click','popstate', 'onload'].forEach( evt =>
window.addEventListener(evt, function () {
requestAnimationFrame(()=>{
if (url !== location.href) {
// do stuff
}
url = location.href;
});
}, true)
);
Is there a better or more generic way to listen for page loads in a SPA?
Most SPAs load website resources on the first page load. Thereafter, the URLs of the website do not change.
To Detect URL Change in JavaScript Without Refresh we use MutationObserver() function. And JavaScript location.
You can use the popstate method to detect those URL changes and make UI changes as needed. window. addEventListener('popstate', function (event) { // The URL changed... }); Yesterday, we learned that the first property passed into the history.
Now that most browser's support MutationObserver
, you can use code like this to detect URL changes in a SPA:
let previousUrl = '';
const observer = new MutationObserver(function(mutations) {
if (location.href !== previousUrl) {
previousUrl = location.href;
console.log(`URL changed to ${location.href}`);
}
});
const config = {subtree: true, childList: true};
observer.observe(document, config);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With