@老虎会游泳,我理解错了?https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/script#attr-defer
defer布尔属性被设定用来通知浏览器该脚本将在文档完成解析后,触发DOMContentLoaded (en-US)事件前执行。
有defer属性的脚本会阻止DOMContentLoaded事件,直到脚本被加载并且解析完成。
@无名啊,问题好像并不是同时触发,而是$(document).ready()事件在DOMContentLoaded事件之后发生。
不过现在研究这个问题无意义了,因为我的代码现在位于立即执行表达式中,总是最先执行。
我确实想到一个解决方法,就是用setTimeout推迟onclick事件的绑定。
$(document).ready(function () {
document.querySelectorAll('.userimg, .userthumb').forEach(img => (img.onclick = function () {
// 链接中的图片不预览
if (0 !== $(this).parents('a').length) return;
let elem = document.querySelector('body');
let viewer = new Viewer(elem, {
hidden: () => viewer.destroy(),
filter(image) {
return image.matches('.userimg, .userthumb');
}
});
viewer.show()
}));
});
@无名啊,只要添加setTimeout,就可以在我的$(document).ready()先执行的情况下,让我的绑定后执行。
$(document).ready(() => {
// 加这个延时,就可以保证晚于任何其他插件执行,以解决和viewer.js的冲突
setTimeout(() => {
document.querySelectorAll('.userimg').forEach(x => {
// 替换掉虎绿林的点击查看大图事件
x._onclick = x.onclick;
x.onclick = function () {
this.src = this._url;
// 再次点击就触发虎绿林的点击查看大图事件
x.onclick = x._onclick;
// 恢复被抑制的图片外层链接
if (x.parentNode._href) {
// 为了防止外层链接被立即触发,所以加个延时
setTimeout(() => x.parentNode.href = x.parentNode._href);
}
};
});
});
});