You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面刷新时Scroll事件未触发,如何让JS在加载及滚动时均执行?

Fix: Header Sticky Class Not Applying on Page Refresh/Load

Got it, let's sort out this issue! The problem with your original code is that it only executes when a scroll event is triggered. That means if you refresh the page while already scrolled past the 170px threshold, the code never runs to add the sticky class to your header.

The Solution: Reusable Logic + Initial Page Load Check

The fix is straightforward: we'll extract the sticky class toggle logic into a reusable function, then run that function both on page load/refresh AND when the user scrolls.

Here's the updated code:

// Extract the sticky toggle logic into a standalone function
function toggleStickyHeader() {
  const scrollPosition = $(window).scrollTop();
  const header = $('.header');
  
  if (scrollPosition > 170) {
    header.addClass('sticky');
  } else {
    header.removeClass('sticky');
  }
}

// Run the function immediately when the page loads/refreshs
toggleStickyHeader();

// Bind the function to the scroll event
$(window).scroll(toggleStickyHeader);

Why This Works:

  • Reusable Function: By putting the logic into toggleStickyHeader(), we avoid repeating code and make future tweaks easier.
  • Initial Execution: Calling toggleStickyHeader() right away checks the scroll position as soon as the page finishes loading, so even if you refresh mid-page, the header gets the correct class immediately.
  • Scroll Event Binding: We still keep the scroll event listener so the class updates as the user scrolls up and down.

Bonus: Add Debouncing for Better Performance

Scroll events fire extremely frequently (hundreds of times per scroll), which can cause unnecessary DOM operations. Adding a debounce function will limit how often our toggle logic runs, improving performance:

// Debounce utility to limit function execution frequency
function debounce(func, delay = 100) {
  let timeoutId;
  return function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(func, delay);
  };
}

// Extract the sticky toggle logic
function toggleStickyHeader() {
  const scrollPosition = $(window).scrollTop();
  const header = $('.header');
  
  scrollPosition > 170 ? header.addClass('sticky') : header.removeClass('sticky');
}

// Create a debounced version of our toggle function
const debouncedToggle = debounce(toggleStickyHeader);

// Initial page load check
toggleStickyHeader();

// Bind the debounced function to scroll event
$(window).scroll(debouncedToggle);

This debounced version waits 100ms after the user stops scrolling before running the logic—enough to keep the UI responsive without overworking the browser.

内容的提问来源于stack exchange,提问作者CharlyAnderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:58:24