I'm dynamically inserting a script element using jQuery. The script loads as expected, but the load event does not fire.
jQuery('<script/>').attr({
type : 'text/javascript',
src : 'http://platform.twitter.com/widgets.js'
}).appendTo('body').load(function(){
/* This alert does not fire: */
alert('I just loaded!');
});
If I use regular JavaScript to insert the element, the load event does fire and can be caught with jQuery.
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = 'http://platform.twitter.com/widgets.js';
document.body.appendChild(e);
jQuery(e).load(function(){
/* This alert does fire: */
alert('I just loaded!');
});
What am I doing wrong?
Use the jQuery.getScript()
[docs] method instead.
$.getScript('http://platform.twitter.com/widgets.js',function(){
alert('I just loaded!');
});
Or, on current versions of jQuery, using the promise pattern as below
$.getScript('http://platform.twitter.com/widgets.js')
.done(function(){
alert('I just loaded!');
})
.fail(function(){
console.log('script could not load');
})
;
EDIT: Removed the code comment that was copied from the question, as it added confusion to the answer. Thanks to @Jeff for pointing it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With