【问题标题】:What is the Proper way to load the Google Javascript Client Library and a custom Endpoint Client Library加载 Google Javascript 客户端库和自定义端点客户端库的正确方法是什么
【发布时间】:2014-06-26 14:32:59
【问题描述】:

我正在使用 Google Javascript 客户端 API,我想知道以下两段代码之间的区别是什么:

//in the html file
<script src="https://apis.google.com/js/client.js?onload=gapiInit"></script>

//in a javscript file
gapiInit = function() {
    alert("Loading the Libs!");

    var numApisToLoad;

    var callback = function(){
        if(--numApisToLoad == 0) {
            alert('APIs Ready!');
            }
    };

    numApisToLoad = 1;

    gapi.client.load('plus','v1',callback);
};

还有这个..

<script>
    // Asynchronously load the client library
    (function() {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/client:plusone.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();
</script>

我在谷歌提供的各种示例中都看到过,谷歌加号登录示例使用后者,而云端点示例使用前者..

他们只是做同样事情的两种方式吗?我使用哪个真的很重要吗?

来自 developer.google.com 的示例

//端点 --
https://developers.google.com/appengine/docs/java/endpoints/consume_js

//加登录(好像两者都做)--
https://developers.google.com/+/web/people/

//只是异步脚本.. --
developer.google.com/+/web/api/javascript

(对不起,这个狡猾的链接,堆栈溢出不会让我放两个以上)

任何见解将不胜感激。

谢谢大家。

【问题讨论】:

    标签: javascript google-app-engine google-plus google-plus-one


    【解决方案1】:

    这个:

    <script src="https://apis.google.com/js/client.js?onload=gapiInit"></script>
    

    在继续之前将完全加载 client.js。确保将其放在页面上的所有标记之后以提高性能。

    此时:

    <script>
        // Asynchronously load the client library
        (function() {
            var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
            po.src = 'https://apis.google.com/js/client:plusone.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
        })();
    </script>
    

    似乎它会同时加载客户端和 plusone js 模块(注意路径中的客户端:plusone)。它将在后台加载。该网址似乎缺少回调:

    https://apis.google.com/js/client:plusone.js?onload=onLoadCallback
    

    如果您想稍后或有条件地加载它,这会带来好处。完成加载后,它将调用您必须定义的 onLoadCallback 函数。

    https://developers.google.com/+/web/api/javascript

    【讨论】:

    • 感谢您的洞察力,所以看起来它们会导致加载客户端和 plus 模块的“状态”相同...?
    • 或者只是在脚本标签中使用async defer...不用恐慌
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多