Execute function after loading all the scripts in pure Javascript

1

I'm creating a plugin for Google Chrome where I inject elements into the page like the FontAwesome and Jquery libraries. These elements that I inject are coming from host's CDN's and need to start a function once they are all validated. to do this, I've developed this function:

var fn = {
    injection : {
        fontAwesome : {
            type : 'link',
            attr : {
                rel : 'stylesheet',
                href : 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css'
            },
            insertBefore : 'head',
            check : true
        },
        jquery : {
            type : 'script',
            attr : {
                src : 'https://code.jquery.com/jquery-2.1.4.min.js'
            },
            insertBefore : 'head',
            check : true
        }
    },
    makeInjection : function(){
        var check = 0, obj = this.injection;
        function bootstrapped(){
            if(check == Object.keys(obj).length){
                fn.init();
            };
        }
        for (var param in obj) {
            var el = document.createElement(obj[param].type), ib;
            obj[param].insertBefore == 'head' ? ib = document.head : ib = document.body;
            for (var attr in obj[param].attr) {
                el.setAttribute(attr,obj[param].attr[attr]);
            };
            ib.insertBefore(el, ib.childNodes[ib.childNodes.length]);
            if(obj[param].hasOwnProperty('check')){
                el.onload = function(){
                    setTimeout(function(){
                        check++;
                        bootstrapped();
                    },100);
                }
            } else {
                setTimeout(function(){
                    check++;
                    bootstrapped();
                },100);             
            }
        };
    },
    init : function(){
        console.log('carrego tudo!');
        return $;
    }
}

My problem is that when I run this script alone, without being compiled inside an extension, it works out that it's a beauty, now when I compile it buga and says that jquery is not loaded. Does anyone have a light there?

    
asked by anonymous 04.09.2015 / 04:27

1 answer

1

I noticed that you assign a function to the load event after entering the resource with .insertBefore() . In this way it is possible that the function assigned to the load event is never executed because the event has already happened at the time of the assignment.

Maybe move the line

ib.insertBefore(el, ib.childNodes[ib.childNodes.length]);

to the end of loop for solve the problem

    
06.11.2015 / 12:23