问题
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