Trying to fire the onload event on script tag

可紊 提交于 2019-11-26 00:37:38

问题


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);

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.


回答1:


You should set the src attribute after the onload event, f.ex:

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

You should also append the script to the DOM before attaching the onload event:

$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/



来源:https://stackoverflow.com/questions/16230886/trying-to-fire-the-onload-event-on-script-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!