为什么不.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.
更多推荐
发布评论