试图在脚本标签上触发 onload 事件

编程入门 行业动态 更新时间:2024-10-25 08:24:19
本文介绍了试图在脚本标签上触发 onload 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试按顺序加载一组脚本,但 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 事件

本文发布于:2023-11-11 18:39:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579255.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   事件   标签   onload

发布评论

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

>www.elefans.com

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