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?