基于用户时段切换网站昼夜版本的JS实现求助(解决页面重复刷新问题)
Hey Yash, no worries at all—let's sort out that annoying infinite refresh problem together! The root cause here is almost certainly that your current code triggers a redirect every single time the page loads, even when the user is already on the correct day or night version. That creates a never-ending loop where the page keeps reloading over and over.
Here's a step-by-step solution tailored for you as a JavaScript beginner:
1. Core Fix: Avoid Redirecting to the Same Domain
First, we need to check which domain the user is currently on before deciding to redirect. This stops the loop immediately.
Working Code Example
// Grab the current website domain (e.g., "yashtest.com" or "dark.yashtest.com") const currentDomain = window.location.hostname; // Define our two version domains const dayDomain = "yashtest.com"; const nightDomain = "dark.yashtest.com"; // Get the current hour (24-hour format: 0 = midnight, 23 = 11 PM) const currentHour = new Date().getHours(); // Set your time range for night mode (adjust these numbers to fit your needs!) const isNightTime = currentHour >= 20 || currentHour < 6; // Figure out which domain we should send the user to const targetDomain = isNightTime ? nightDomain : dayDomain; // Only redirect if we're NOT already on the target domain if (currentDomain !== targetDomain) { // Build the full URL to redirect to, keeping the current page path and any query parameters const targetUrl = `http://${targetDomain}${window.location.pathname}${window.location.search}`; // Send the user to the correct version window.location.href = targetUrl; }
Key Details Explained
currentDomaincheck: This is the critical line that prevents the infinite loop. We only redirect if the user isn't already on the right version.- Preserving path/params: The
window.location.pathnameandwindow.location.searchparts make sure users stay on the same page they were trying to access (e.g., if they went toyashtest.com/blog, they'll be sent todark.yashtest.com/bloginstead of the homepage). - Adjustable time range: Change
20and6to whatever hours make sense for your "night" period.
2. Bonus: Add User Manual Override (Optional But User-Friendly)
Users might want to switch to night mode during the day (or vice versa) regardless of the time. We can use localStorage to remember their choice so the auto-switch doesn't override it.
Example with Manual Toggle
First, update your auto-switch code to check for saved preferences:
// Check if the user has a saved theme preference const savedPreference = localStorage.getItem("themeChoice"); let isNightTime; if (savedPreference) { // Use the user's saved choice if it exists isNightTime = savedPreference === "dark"; } else { // Fall back to time-based check if no preference is saved const currentHour = new Date().getHours(); isNightTime = currentHour >= 20 || currentHour < 6; } // Rest of the redirect logic stays the same...
Then add a toggle button to your HTML:
<button id="toggleTheme">Switch to {{isNightTime ? 'Day' : 'Night'}} Mode</button>
And add this JavaScript to handle the button click:
document.getElementById("toggleTheme").addEventListener("click", () => { // Flip the current preference const newChoice = isNightTime ? "light" : "dark"; // Save the choice to localStorage localStorage.setItem("themeChoice", newChoice); // Redirect to the correct version const targetUrl = newChoice === "dark" ? "http://dark.yashtest.com" : "http://yashtest.com"; window.location.href = targetUrl; });
Where to Put the Code
For best results, place your JavaScript code right before the closing </body> tag in your HTML. This ensures the code runs after the page content loads, which avoids any unexpected issues.
内容的提问来源于stack exchange,提问作者Yash




