Pregunta

I am playing with the Google Javascript client API and am wondering what the difference between the two following pieces of code is:

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

and this..

<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>

I have seen both in various examples that google provides, the Google Plus Sign in example use the latter while the cloud endpoint examples use the former..

Are they just two ways of doing the exact same thing? and does it really matter which I use?

Examples from developer.google.com

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

//Plus Login (seems to do both) --
https://developers.google.com/+/web/people/

//just the async script.. --
developers.google.com/+/web/api/javascript

(sorry for the dodgy link, stack overflow would not let me put more than two in)

Any insight would be much appreciated.

Thanks everyone.

¿Fue útil?

Solución

This:

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

Will fully load client.js before continuing. Make sure you put it after all markup on the page to increase performance.

While this:

<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>

Seems like it will load both the client and plusone js modules (notice in the path the client:plusone). It will load in the background. The url seems to be missing a callback though:

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

This has the benefit of if you wanted to load it later or conditionally. When its done loading it will call the onLoadCallback function that you must define.

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top