Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't jQuery's load event fire on dynamically inserted script elements?

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?

like image 862
John Blackbourn Avatar asked Jun 26 '11 17:06

John Blackbourn


1 Answers

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.

like image 73
user113716 Avatar answered Sep 19 '22 09:09

user113716