试图在脚本标签上触发 onload 事件 [英] Trying to fire the onload event on script tag

查看:53
本文介绍了试图在脚本标签上触发 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.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);

我猜当使用 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() 方法:http://api.jquery.com/jQuery.getScript/

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/

这篇关于试图在脚本标签上触发 onload 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆