当脚本插入DOM时jQuery .on()没有绑定

我有一个包含自定义jQuery事件处理程序的远程javascript文件。 当它作为元素插入DOM时,不会注册自定义事件处理程序。

但是,如果我添加与直接JS( ... )完全相同的脚本,则会注册事件处理程序,并且所有内容都按预期执行。

当脚本作为远程文件插入时,为什么不将事件处理程序绑定在jQuery中?

远程文件,包含自定义事件处理程序:

 console.log('Before custom event handler'); $('button').on('customEvent', function(){ console.log('customEvent Caught'); }); 

https://gist.github.com/2767385

将脚本插入DOM的( 非工作 )javascript:

 var scriptNode = document.createElement('script'); scriptNode.src = 'https://gist.github.com/raw/2767385/b9ddea612ff60b334bd2430e59903174e527a3b5/gistfile1.js'; document.body.appendChild(scriptNode); 

工作替代 )javascript,它将脚本作为内联插入到DOM中:

 var scriptText = "console.log('Before custom event handler'); $('button').on('customEvent', function(){ console.log('customEvent Caught'); });", scriptNode = document.createElement('script'); scriptNode.appendChild(document.createTextNode(scriptText)); document.body.appendChild(scriptNode); 

触发事件:

 $('button').triggerHandler('customEvent'); 

正确读取JS,并正确执行处理程序。

JSFiddles

远程文件 – 非工作示例: http : //jsfiddle.net/3CfFM/3/
使用文本 – 工作替代方案: http : //jsfiddle.net/3CfFM/2/

发生了什么?

当脚本作为远程文件插入时,为什么不将事件处理程序绑定在jQuery中?

你错了。 与远程脚本一起使用时绑定事件处理程序; 它只需要一点时间。 浏览器需要在绑定处理程序之前发出HTTP请求。 这意味着您没有捕获使用triggerHandler('customEvent')触发的原始​​事件,因为它的冒泡和捕获已经完成。

如果等待一秒钟,然后再次单击该按钮,您将看到事件处理程序确实已绑定。 你也可以通过延迟你的triggerHandler调用来看到这个,直到脚本加载为止:

 $('button').click(function() { var scriptNode = document.createElement('script'); scriptNode.src = 'https://gist.github.com/raw/2767385/897cffca74411dbb542c0713bacb5a4048d6708b/gistfile1.js'; scriptNode.onload = function() { $('button').triggerHandler('customEvent'); }; document.body.appendChild(scriptNode); }); 

http://jsfiddle.net/3CfFM/4/