non-passive事件监听器违规:onchange函数移文件夹后失效求助
Hey there, let’s work through this problem step by step—you’ve got two linked issues here: a scroll-blocking event listener warning, and a function that stopped working entirely after moving your JS file to a separate folder. Let’s tackle them one by one!
First: Get Your Broken Function Working Again
The warning is just a performance heads-up, but the function not running is the bigger priority. Here’s what to check:
- Double-check your JS file path: When you moved the file to a new folder, did you update the
<script>tag in your HTML? For example, if you movedscript.jsinto ajs/subfolder, your tag needs to change from<script src="script.js"></script>to<script src="js/script.js"></script>. A wrong path will cause a 404 error (check the "Network" tab in your browser’s dev tools to confirm this). - Make sure your code runs after the DOM is ready: If your function tries to attach an event listener to an element that hasn’t loaded yet, it’ll fail. Wrap your event listener code in a
DOMContentLoadedhandler to fix this:document.addEventListener('DOMContentLoaded', function() { // Your mousewheel event listener code goes here }); - Clear your browser cache: Sometimes browsers hang onto old versions of your JS file. Hit
Ctrl+Shift+R(orCmd+Shift+Ron Mac) to force a fresh reload.
Next: Fix the Non-Passive Event Listener Warning
Once your function is working again, that scroll-blocking warning will still pop up. Here’s how to resolve it:
- The warning happens because browsers can’t optimize scrolling performance if your
mousewheellistener might callevent.preventDefault()(which blocks the default scroll behavior). To fix this, mark the listener aspassive—this tells the browser your handler won’t block scrolling. - Before (problematic code):
someElement.addEventListener('mousewheel', yourScrollHandler); - After (fixed code):
someElement.addEventListener('mousewheel', yourScrollHandler, { passive: true }); - Important note: If your handler does use
event.preventDefault(), settingpassive: truewill make that call ignored by the browser. If you absolutely need to block scrolling, you’ll have to weigh the performance tradeoff—alternatively, see if you can achieve the same effect with CSS instead of JS to avoid the warning entirely.
Quick Extra Check
The reason other functions in the same file work fine is likely because they don’t depend on the mousewheel event or have simpler execution logic (like not needing to target a specific DOM element right away). Focus on the path and DOM readiness for the broken function first.
Your original error message for reference:
[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the...
内容的提问来源于stack exchange,提问作者Beks

