开发者

Load jQuery script after JavaScript script has finished

开发者 https://www.devze.com 2023-02-08 00:38 出处:网络
Similar to 开发者_如何学Gothe way jQuery loads after the document has loaded I need a certain bit of jQuery after a JavaScript script has FINISHED.

Similar to 开发者_如何学Gothe 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?


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


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.


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号