如何使用JS滚动到动态加载、高度变化的网页底部?
Great question! When you're dealing with pages that load new content automatically as you scroll (think infinite scroll feeds on social media or product listing pages), a single window.scrollTo(0, document.body.scrollHeight) call just won't cut it—since the page height keeps growing every time new content loads. Here's how to scroll all the way until there's no more content left to load:
Method 1: Recursive Scroll with Loading Delay
This approach uses a recursive function that scrolls to the current bottom, waits a bit for new content to load, then checks if the page height has changed. If it has, it repeats the process; if not, we've reached the true bottom.
function scrollToBottom() { // Store the current page height before scrolling const initialHeight = document.body.scrollHeight; // Scroll to the current bottom (smooth scroll is optional) window.scrollTo({ top: initialHeight, behavior: 'smooth' }); // Wait for content to load—adjust the timeout based on the site's load speed setTimeout(() => { const newHeight = document.body.scrollHeight; // If height changed, there's new content—scroll again if (newHeight > initialHeight) { scrollToBottom(); } else { console.log("Reached the true bottom of the page!"); } }, 1000); // 1 second delay; tweak this if the site loads faster/slower } // Start the scrolling process scrollToBottom();
Method 2: Interval-Based Scroll Check
If recursion isn't your style, you can use an interval that repeatedly scrolls and checks for new content, stopping once the page height stops changing.
let scrollInterval = setInterval(() => { const initialHeight = document.body.scrollHeight; window.scrollTo(0, initialHeight); setTimeout(() => { const newHeight = document.body.scrollHeight; // Stop the interval when no new content is loaded if (newHeight === initialHeight) { clearInterval(scrollInterval); console.log("No more content to load—we're at the bottom!"); } }, 800); // Adjust delay based on how fast the site loads content }, 1000); // Repeat the scroll check every 1 second
Key Tips:
- Tweak Timeouts: Every site loads content at different speeds. If the script stops too early, increase the timeout values. If it waits too long, decrease them.
- Smooth Scroll Toggle: Remove the
behavior: 'smooth'option if you want instant, jump-style scrolling instead of gradual movement. - Edge Cases: Some sites limit how much content they load (e.g., only 10 pages of results). The script will automatically stop once no new content is added, which is exactly what we want.
内容的提问来源于stack exchange,提问作者KangarooChief

