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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:45:05  来源:igfitidea点击:

Trying to fire the onload event on script tag

javascriptjqueryonload

提问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 srcattribute afterthe onloadevent, f.ex:

您应该在事件之后设置src属性,例如:onload

el.onload = function() { //...
el.src = script;

You should also append the script to the DOM beforeattaching the onloadevent:

附加onload事件之前,您还应该将脚本附加到 DOM :

$body.append(el);
el.onload = function() { //...
el.src = script;

Remember that you need to check readystatefor IE support. If you are using jQuery, you can also try the getScript()method: http://api.jquery.com/jQuery.getScript/

请记住,您需要检查readystateIE 支持。如果你使用的是 jQuery,你也可以试试这个getScript()方法:http: //api.jquery.com/jQuery.getScript/