When working on web development projects, you might find yourself needing to detect if a page gets reloaded or refreshed using JavaScript. This can be crucial for various reasons like handling form submissions or updating content dynamically. Fortunately, JavaScript provides a simple way to determine if a page is reloaded or refreshed.
One common method to check if a page gets reloaded is by using the `performance.navigation` object in JavaScript. This object gives you access to performance-related information about the current browsing session. To utilize this feature, you can use the `type` property of `performance.navigation` to distinguish between different types of page navigations.
Here's how you can implement this in your JavaScript code:
if (performance.navigation.type === 1) {
console.log("Page reloaded");
} else if (performance.navigation.type === 0) {
console.log("Page refreshed");
} else {
console.log("Page loaded for the first time");
}
In this code snippet, we first check if the `type` property of `performance.navigation` is equal to `1`, which indicates a page reload. If it is `0`, it means the page is being refreshed. Lastly, if the `type` is neither `1` nor `0`, it means that the page is loaded for the first time.
Another approach to detect page reload or refresh is by comparing the entries in the window's performance session history. The `performance.getEntriesByType("navigation")` function can be used to retrieve a list of performance entries related to navigation events.
Here's a sample code snippet to demonstrate this method:
window.addEventListener('load', function() {
var entryTypes = performance.getEntriesByType("navigation");
if (entryTypes.length && entryTypes[0].type === "reload") {
console.log("Page reloaded");
} else {
console.log("Page refreshed or loaded for the first time");
}
});
In this code, the `performance.getEntriesByType("navigation")` function is used to get navigation-related performance entries. By checking the type of the first entry, you can determine if the page has been reloaded.
These two methods provide you with effective ways to check if a page is reloaded or refreshed in JavaScript. You can choose the one that best suits your specific needs and integrate it into your web development projects for better control and customization. Happy coding!