Binding LOAD event to a SCRIPT tag may not work
Hello,
I'm trying to display a message when a SCRIPT tag is loaded to know
when an external script has been loaded.
I am trying to do it as follow:
---------------
var script = $('<script><\/script>')
.bind('load', function(e) { // attach onload event handler
alert('Script loaded: ' + this.src);
})
.attr('src', url); // a valid url of a javascript file: ie:
http://jqueryjs.googlecode.com/files/jquery-1.2.3.js
---------------
Then, I add my script to the HEAD tag:
---------------
script.appendTo($('head'));
---------------
If I use the method "appendTo" to add it to the HEAD tag, it seems to
work as the external javascript file is loaded and executed (and also
removed from the DOM just after).
But the onload event hasn't been raised and no message is shown.
On the other hand, if I add this script with the native methods:
---------------
$('head')[0].appendChild(script[0]);
---------------
It does work!
The code is executed and the message is displayed.
I read somewhere that there's a jQuery method to run a script's source
code from its DOM and while it adds it to the document, it will also
remove it straight away.
Maybe it's being removed too quickly and the onload event hasn't the
time to be raised.
Do you know if it is as per design or is it faulty?
Regards,
Kayhadrin