Run function after loading all scripts in pure Javascript

Asked

Viewed 385 times

1

I’m creating a plugin for Google Chrome where I inject elements into the page like the Fontawesome and Jquery libraries. These elements I inject are coming from CDN’s host and need to start a function as soon as they are all validated. to do this, I 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 within an extension, it works which is a beauty, now when I compile it Buga and says that jquery is not loaded. Someone there has a light?

1 answer

1


I notice you assign a function to the event load after inserting the resource with .insertBefore(). In this way it is possible that the function assigned to the event load never run, as the event already happened at the time of the assignment.

Maybe move the line

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

towards the end of the loop for solve the problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.