Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

javascript - Trying to fire the onload event on script tag

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...