Dan Getz
Dan Getz

Reputation: 55

Loading Google jsapi asynchronously

There was an issue with Google charts today so we're trying to fail gracefully if we can't load the js file. The following works fine:

<script type="text/javascript" src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22visualization%22%2C%22version%22%3A%221.0%22%2C%22packages%22%3A%5B%22corechart%22%5D%7D%5D%7D"></script>

The problem is that it will block running other code as it is waiting for the script to time out.

The code below loads,

<script type="text/javascript">
$.ajax({
    url: 'https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22visualization%22%2C%22version%22%3A%221.0%22%2C%22packages%22%3A%5B%22corechart%22%5D%7D%5D%7D',
    dataType: 'script',
    cache: true, // otherwise will get fresh copy every page load
    success: function() {
      google.load("visualization", "1", {packages:["corechart"]}); 
    }
});
</script>

but it errors when I try to use a visualization such as

var data = new google.visualization.DataTable();

Is what I'm doing possible or are we stuck with the problem of if Google is having issues, we just have to wait for the js file to timeout and move on?

Thanks!

Upvotes: 5

Views: 6553

Answers (2)

viz-tybs
viz-tybs

Reputation: 471

Since you're calling the google.load function on success, the ?autoload=... stuff is redundant.

Just change your url to //www.google.com/jsapi, and add a 'callback' to the load call to make sure that your drawChart code is called when corechart completes.

Here's a JSFiddle and a code snippet: http://jsfiddle.net/c56pC/2/

<script type="text/javascript">
$.ajax({
    url: '//www.google.com/jsapi',
    dataType: 'script',
    cache: true,
    success: function() {
        google.load('visualization', '1', {
            'packages': ['corechart'],
            'callback': drawChart
        });
    }
});
</script>

Upvotes: 5

Blazemonger
Blazemonger

Reputation: 92983

Your script won't execute once it's downloaded via AJAX. You want to use $.getScript():

$.ajaxSetup({ cache: true });
var url = 'https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22visualization%22%2C%22version%22%3A%221.0%22%2C%22packages%22%3A%5B%22corechart%22%5D%7D%5D%7D';
$.getScript(url, function() {
    google.load("visualization", "1", {packages:["corechart"]}); 
});

Upvotes: 2

Related Questions