nkcmr
nkcmr

Reputation: 11000

Load jQuery script after JavaScript script has finished

Similar to the way jQuery loads after the document has loaded I need a certain bit of jQuery after a JavaScript script has FINISHED.

I am loading contact data from Google Data API and the div where the data shows up needs to be completely loaded (by the JavaScript) to be accessible by the jQuery if I'm right.

Is there any way to do this?

Upvotes: 2

Views: 3571

Answers (4)

Krule
Krule

Reputation: 6476

Try head.js

It allows to define exactly when (after specific script or after all of them have been loaded) you want to execute particular piece of code.

Not to mention it is by itself very neat.

Upvotes: 1

Evan Nagle
Evan Nagle

Reputation: 5133

Let's say you're waiting for Google Analytics to load. Now, you know that when Google Analytics loads, _gaq will be registered on the DOM. So, barring all other (better) asynchronous options, you can create a function that waits for the existence of _gaq:

waitForGaq = function(fn, attemptsLeft) {
    var tick = attemptsLeft || 30; 

    if (typeof(_gaq) != 'object' || !_gaq._getAsyncTracker) {
        //_gaq isn't registered yet
        if (tick > 1) {
            //recurse
            setTimeout(function() {
                waitForGaq(fn, tick - 1);
            }, 100)
        }
        else {
            //no ticks left, log error
            log('failed to load window.gaq');
        }
    }
    else {
        //gaq is loaded, fire fn
        fn();
    }
}

So, any code needs to run AFTER _gaq is registered, you can add to the page thusly:

waitForGaq(function() {
    //here's all my code...
});

To reiterate: recursing like this is only necessary if the script that you're adding doesn't offer an asynchronous way of interacting with the library. Google Analytics, for one, is kind of a moot example as it offers a cleaner approach:

http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html

Upvotes: 5

Victor
Victor

Reputation: 4721

if i understand correctly, you want to do something like:

<script>
// your javascript code
</script>
<script>
//your jquery code
</script>

Upvotes: 0

Raynos
Raynos

Reputation: 169373

inject a tag directly after the original with the jQuery code you need to run

<script src="foo" id="bar">

$("#bar").after(
    $("<script>").text("some code")
);

Upvotes: 0

Related Questions