Amap Series (2): Eliminate browser console warning Added non-passive event listener to a scroll-blocking ‘touchstart‘ event…

  • The warning is as follows:

  • Although it does not affect the normal operation of the code, such long warnings are indeed a bit uncomfortable for programmers, so solve them next! !
  • First of all, make sure that this warning is definitely not caused by our code! So what is the reason?

  •  Use Youdao Translation and combine it with your own understanding: You need to add a passive event listener to prevent 'touchstart, touchmove' events. Consider adding a 'passive' event to let the page handle more responses (processing faster)
  • Cause of occurrence:Chrome has added a new event capture mechanism Passive Event Listeners hearing aid)
  • The main function is to make the page slide more smoothly, mainly used to improve the performance of mobile sliding behavior (note:When the browser originally responded to the default event, it had to Check whether the default event has been canceled. This will cause a slight delay before responding to the sliding operation.Starting from chrome56, touchstart and registered on the window, document and body The touchmove event handler will default to passive: true. The browser can scroll immediately by ignoring preventDefault().)
  • Passive Event Listeners: It tells whether the event listener in the previous page will be called internallypreventDefault function to prevent the default behavior of the event so that the browser can make better decisions based on this information to optimize page performance. When the value of the attribute passive is true, it means that the preventDefault function will not be called internally in the listener to prevent the default sliding behavior. The Chrome browser calls this type of listener a passive listener. Currently, Chrome mainly uses this feature to optimize the sliding performance of the page, so the Passive Event Listeners feature currently only supports mousewheel/touch related events.
  • Solution:
npm i default-passive-events -S
或者
yarn add default-passive-events -S 

main.js中:
import 'default-passive-events'
  • But if the following error occurs when performing certain operations: Related events.

  •  Translation: Cannot preventDefault in passive event listener call
  • Goal:How to prevent the console from prompting and preventDefault() to be effective
  • Solution: (Online solution may be useful elsewhere)
// 1、明确声明为不是被动的
window.addEventListener('touchmove', func, { passive: false })
window.addEventListener('touchstart', this.func, { passive: false })

func(event){
    event.preventDefault()
}

// 2、针对涉及到的dom, 应用 CSS 属性 touch-action: none; 这样任何触摸事件都不会产生默认行为,但是 touch 事件照样触发。

// 3、注意不要安装前面的依赖default-passive-events,如果安装了记得卸载
npm uninstall default-passive-events
或者
yarn remove default-passive-events

Guess you like

Origin blog.csdn.net/qq_45796592/article/details/134286011