在我的网站(使用jQuery 1.11)中,我必须使用一个外部脚本,在我为其指定的div中呈现自己的HTML。由于需要相当长的时间,因此推迟了。
现在,为了知道它的内容何时被加载,我创建了一个函数,在一个小的超时后,尝试通过$(selector).length
调用检测内容,并根据这个结果,它或者a)设置更长的超时时间再次调用自身,或者b)找到内容并设置我需要在加载的内容上设置的.on()
类事件。
有更简单的方法吗?我觉得这很复杂。注意:
.getScript()
来启动回调设置答案 0 :(得分:1)
有更简单的方法吗?
如果不做你已经排除的事情,就不要达到你在问题标题中指定的目标。
但是,您可以使用delegated events。
在脚本运行之前将事件处理程序绑定到您知道存在的元素,并等待事件冒泡到它。
$("#div-I-specify-for-it").on("click", ".element-inside-div", (event) => alert("example"));
答案 1 :(得分:1)
如果您可以编辑外部脚本:
在加载外部脚本之前,创建一些事件处理程序,然后在算法完成后,只发送预期的事件。您的所有JS代码共享相同的window.document
,因此您可以使用它:
window.document.addEventListener('plugin', (event) => {
// Your script have sent the event
})
然后在插件端发送事件
const event = new CustomEvent('plugin', {
detail: {
// Here I send the current plugin script uri, can be used if the event handler is used by several script (not your usecase)
sourcePath: document.currentScript.src,
},
})
document.dispatchEvent(event)
我们使用scriptjs来动态加载外部JS文件,效果很好。