问题
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?
回答1:
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
回答2:
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.
回答3:
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")
);
回答4:
if i understand correctly, you want to do something like:
<script>
// your javascript code
</script>
<script>
//your jquery code
</script>
来源:https://stackoverflow.com/questions/4881289/load-jquery-script-after-javascript-script-has-finished