JavaScript脚本完成后加载jQuery脚本 [英] load jQuery script after JavaScript script has finished

查看:55
本文介绍了JavaScript脚本完成后加载jQuery脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于在文档加载后jQuery加载的方式,在JavaScript脚本完成后,我需要一定程度的jQuery.

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

如果我是对的话,我正在从Google Data API和显示数据的div加载联系人数据,则需要完全加载(通过javascript),以便jQuery可以访问.

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.

有什么办法吗?

推荐答案

假设您正在等待Google Analytics(分析)的加载.现在,您知道在加载Google Analytics(分析)时,_gaq将在DOM上注册.因此,除所有其他(更好的)异步选项外,您可以创建一个函数,等待_gaq的存在:

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

因此,任何需要在_gaq之后运行的代码都已注册,因此您可以将其添加到页面中:

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

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

要重申:仅当您要添加的脚本不提供与库进行交互的异步方式时,才需要进行此类递归.一方面,Google Analytics(分析)是一个有争议的例子,因为它提供了一种更简洁的方法:

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

这篇关于JavaScript脚本完成后加载jQuery脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆