我正在尝试按顺序加载一组脚本,但 onload 事件没有为我触发.
I'm trying to load a set of scripts in order, but the onload event isn't firing for me.
var scripts = [ '//cdnjs.cloudflare/ajax/libs/less.js/1.3.3/less.min.js', '//cdnjs.cloudflare/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);我猜当使用 jQuery 将元素附加到 DOM 时,不会触发像 el.onload 这样的本机事件.如果我使用本机 document.body.appendChild(el) 那么它会按预期触发.
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.
推荐答案你应该设置 src 属性 after onload 事件,f.例如:
You should set the src attribute after the onload event, f.ex:
el.onload = function() { //... el.src = script;您还应该在附加 onload 事件之前将脚本附加到 DOM:
You should also append the script to the DOM before attaching the onload event:
$body.append(el); el.onload = function() { //... el.src = script;请记住,您需要检查 readystate 以获取 IE 支持.如果您使用 jQuery,您还可以尝试 getScript() 方法:api.jquery/jQuery.getScript/
Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: api.jquery/jQuery.getScript/
更多推荐
试图在脚本标签上触发 onload 事件
发布评论