TJR
TJR

Reputation: 6587

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 ?

Upvotes: 9

Views: 3517

Answers (5)

fka
fka

Reputation: 420

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

Upvotes: 3

GGG
GGG

Reputation: 817

It looks like your class has a jQuery dependancy, ideally you should not have that dependancy.

Nonetheless if you are looking for an easy way to load jQuery dynamically, maybe this would help:

function onReady(){
    // My Custom Ready state. lets go wild here.
}

if (typeof jQuery === undefined || jQuery.fn.jquery !== '1.7.2') {

    var jScript = document.createElement('script');
    jScript.setAttribute("type", "text/javascript");
    jScript.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js")

    //Run onReady() once jQuery and document have loaded
    jScript.onload = function () { //Add on load Event delegate
        //JQuery is Loaded!! so you can do whatever you want with it to deligate.
        $(document).ready(onReady)
    }; 
    jScript.onreadystatechange = function () { //Same thing but for IE
        if (this.readyState == 'complete' || this.readyState == 'loaded')(function () {
            //JQuery is Loaded!! so you can do whatever you want with it to deligate.
            $(document).ready(onReady)
        });
    } 

    // Append Script to the Head
    document.getElementsByTagName("head")[0].appendChild(script_tag);

} else {
    // JQuery Exists so lets just use it
    $(document).ready(onReady);
}

Upvotes: 1

freakish
freakish

Reputation: 56577

How about using custom Events? Something like this:

var CustomEvent = function() {
    this.eventName = arguments[0];
    var eventAction = null;
    this.subscribe = function(fn) {
        eventAction = fn; // you can customize this to hold array of handlers
    }; 
    this.fire = function(sender, eventArgs) {
        if (eventAction != null) {
            eventAction(sender, eventArgs);
        } else {
            alert('No ' + mEventName + ' handler!');
        }
    };
};

Now you can define something like this:

var myEvent = new CustomEvent("Framework Loaded");
myEvent.subscribe(function(sender, eventArgs) {
    alert('Framework loaded! Hurray!');
    // jQuery goes here
});

and after loading framework for example jQuery you just do this:

myEvent.fire(null, { framework: 'jQuery' });

(you should put the code probably somewhere in XHR handler).

Also if you make it fire after DOM loaded then you can forget about jQuery's $(document).ready(...) wrapper.

Upvotes: 2

Denis Ermolin
Denis Ermolin

Reputation: 5556

You can use this small library to execute script after loading: Yepnope javascript loader

Also you can download scripts via ajax call. And in success callback append it to the document and execute script's code. But this approach already used in Yepnope library.

Upvotes: 0

reach4thelasers
reach4thelasers

Reputation: 26909

The JQuery document.ready function basically does this:

window.onload = function ()
{
Javascript code goes here
}

Which has no dependencies on external libraries and will run your Javascript when the document has loaded.

You might also want to look at require.js

Upvotes: 0

Related Questions