在建设网站的过程中,使用谷歌Chrome浏览网站,发现控制台一直频繁出现一条名为“[Violation] Added non-passive event listener to a scroll-blocking 'touchstart' event.”的错误,翻译成中文为“[违规]为滚动阻塞 “touchstart ”事件添加了非被动事件监听器。”,查询了许多资料,发现造成这个错误的原因是因为jQuery无法添加对被动监听器的支持,尤其是在网站引用了jQuery 3及之前的版本中出现。
解决方法是在引用完jQuery.js之后,添加以下代码
jQuery.event.special.touchstart = { setup: function( _, ns, handle ) { this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") }); } }; jQuery.event.special.touchmove = { setup: function( _, ns, handle ) { this.addEventListener("touchmove", handle, { passive: !ns.includes("noPreventDefault") }); } }; jQuery.event.special.wheel = { setup: function( _, ns, handle ){ this.addEventListener("wheel", handle, { passive: true }); } }; jQuery.event.special.mousewheel = { setup: function( _, ns, handle ){ this.addEventListener("mousewheel", handle, { passive: true }); } };
当然许多插件均会出现类似的错误,你只需要在代码中添加{ passive: true}
便可以解决这类警告。
例如如果网站引用了swiper.js,同行会出现此警告,你只需要将a.addEventListener(t.start, this.onTouchStart, !1)
修改为a.addEventListener(t.start, this.onTouchStart, { passive: true })
便可以轻松解决这类警告了。
上一篇:免费企业邮箱最高100G容量