Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute javascript before dom is loading

I want to develop a handle javascript class that handle used frameworks, among other things.

For example:

myClass.addFramework('jQuery'); // just an example

It works fine and my class add the framework - but if there any jQuery code in it, it wouldn't work, because the framework is loaded after the dom is ready, so a default jQuery snippet like jQuery(document).ready(function(){}); can't work, because 'jQuery' isn't already defined.

Is there any solution to that I can script a 'fix' that before the rest of the dom is beginning to loading all my addFramework methods must be executed ?

like image 708
TJR Avatar asked Apr 26 '12 09:04

TJR


1 Answers

You should use the onload event while creating script tag. You can use like this:

myClass.addFramework('jQuery', function () {
    // do stuff after jquery loaded.
});

You can implement it like that:

myClass.addFramework = function (name, onload) {
    var _script = document.createElement('script');
    _script.onload = function () {
        onload();
    }
    _script.onreadystatechange = function () {
        if (this.readyState == 'complete') onload();
    }
    _script.src = myClass.FRAMEWORK_BASE + '/' + name + '.js';
    document.getElementsByTagName('head')[0].appendChild(_script);
};
like image 95
fka Avatar answered Sep 17 '22 13:09

fka