jQuery .on() not bound when script inserted into the DOM

為{幸葍}努か 提交于 2020-01-05 02:44:06

问题


I have a remote javascript file containing a custom jQuery event handler. When this is inserted into the DOM as a <script src='...'></script> element, the custom event handler is not registered.

However, if I add the exact same script as straight JS (<script>...</script>), the event handler is registered, and everything executes as expected.

Why isn't the event handler being bound in jQuery when the script is inserted as a remote file?

Example

The remote file, containing the custom event handler:

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

https://gist.github.com/2767385

The (non-working) javascript which inserts the script into the DOM:

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

The (working alternative) javascript which inserts the script as inline into the 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);

Triggering the event:

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

The JS is correctly read, and the handler is correctly executed.

JSFiddles

Remote file - non-working example: http://jsfiddle.net/3CfFM/3/
Using Text - working alternative: http://jsfiddle.net/3CfFM/2/

What's happening?

Why isn't the event handler being bound in jQuery when the script is inserted as a remote file?


回答1:


You're mistaken. The event handler is being bound when used with a remote script; it simply takes a little longer. The browser needs to make an HTTP request before it binds the handler. This means that the original event you trigger with triggerHandler('customEvent') is not captured, since its bubbling and capturing has already completed.

If you wait a second, then click the button again, you will see that the event handler has indeed been bound. You can also see this by delaying your triggerHandler call until the script has loaded:

$('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/



来源:https://stackoverflow.com/questions/10698177/jquery-on-not-bound-when-script-inserted-into-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!