为什么jQuery的加载事件不会触发动态插入的脚本元素? [英] Why won't jQuery's load event fire on dynamically inserted script elements?

查看:57
本文介绍了为什么jQuery的加载事件不会触发动态插入的脚本元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery动态插入一个脚本元素。脚本按预期加载,但加载事件不会触发。

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!');
});

如果我使用常规JavaScript来插入元素,则load事件会触发并可以使用jQuery捕获。

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!');
});

我做错了什么?

推荐答案

使用 jQuery.getScript() [docs] 方法。

$.getScript('http://platform.twitter.com/widgets.js',function(){
    alert('I just loaded!');
});

或者,在当前版本的jQuery上,使用下面的promise模式

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');
  })
;






编辑已删除从问题中复制的代码注释,因为它给答案增加了混淆。感谢 @Jeff 指出它。


Removed the code comment that was copied from the question, as it added confusion to the answer. Thanks to @Jeff for pointing it out.

这篇关于为什么jQuery的加载事件不会触发动态插入的脚本元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆