为什么不.on('load',...)触发脚本标记的回调?(Why doesn't .on('load', …) fire the callback

系统教程 行业动态 更新时间:2024-06-14 16:57:39
为什么不.on('load',...)触发脚本标记的回调?(Why doesn't .on('load', …) fire the callback for a script tag?)

我有以下代码加载外部脚本,并应该在加载时执行一些代码:

$('<script/>', { type: 'text/javascript', src: 'https://raw.github.com/einars/js-beautify/master/beautify.js' }).on('load', function() { alert('jsb loaded' + typeof js_beautify); }).appendTo('body');

但是,事件永远不会触发 - 即使脚本正确加载,也经过验证

window.setTimeout(function() { alert(typeof js_beautify); }, 1000);

警报function很好。

演示: http : //jsfiddle.net/ThiefMaster/x2b9x/

I have the following code which loads an external script and is supposed to execute some code when it's loaded:

$('<script/>', { type: 'text/javascript', src: 'https://raw.github.com/einars/js-beautify/master/beautify.js' }).on('load', function() { alert('jsb loaded' + typeof js_beautify); }).appendTo('body');

However, the event never fires - even though the script is properly loaded, as verified with

window.setTimeout(function() { alert(typeof js_beautify); }, 1000);

which alerts function just fine.

Demo: http://jsfiddle.net/ThiefMaster/x2b9x/

最满意答案

你应该调用$.getScript() ,它完全正确,并且正常工作。

You should call $.getScript(), which does exactly that, and works correctly.

更多推荐

本文发布于:2023-04-13 11:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/b5ff7299b79ce5f74c28578bc29c64ae.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   脚本   标记   load   tag

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!