jQuery 试图在脚本标签上触发 onload 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16230886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to fire the onload event on script tag
提问by chovy
I'm trying to load a set of scripts in order, but the onload event isn't firing for me.
我正在尝试按顺序加载一组脚本,但 onload 事件没有为我触发。
var scripts = [
'//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js',
'//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.min.js',
MK.host+'/templates/templates.js'
];
function loadScripts(scripts){
var script = scripts.shift();
var el = document.createElement('script');
el.src = script;
el.onload = function(script){
console.log(script + ' loaded!');
if (scripts.length) {
loadScripts(scripts);
}
else {
console.log('run app');
MK.init();
}
};
$body.append(el);
}
loadScripts(scripts);
I guess native events like el.onload don't fire when jQuery is used to append the element to the DOM. If I use native document.body.appendChild(el)
then it fires as expected.
我猜当使用 jQuery 将元素附加到 DOM 时,不会触发像 el.onload 这样的本机事件。如果我使用本机,document.body.appendChild(el)
那么它会按预期触发。
回答by David Hellsing
You should set the src
attribute afterthe onload
event, f.ex:
您应该在事件之后设置src
属性,例如:onload
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM beforeattaching the onload
event:
在附加onload
事件之前,您还应该将脚本附加到 DOM :
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
请记住,您需要检查readystate
IE 支持。如果你使用的是 jQuery,你也可以试试这个getScript()
方法:http: //api.jquery.com/jQuery.getScript/