Oct 1, 2010

Google.load vs. $(document).ready()

I am trying to use google visualization in my recent project. After some study, I found it is quite different in terms of usage from my previous mindset. Usually when we need an external javascript library, we go to the web site and download it, and include it in our html file like:

<script type='text/javascript' src='url-to-the-js-lib'></script>

However, this is quite different with google visualization case. A typical usage with google visualization could something like:

<script type='text/javascript' src='http://http://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']});
google.setOnLoadCallback(mydrawfunc);
</script >

the API name "setOnLoadCallback" is misleading to me. It looks like a special hook that get invoked when the visualization (or other google apis) loaded into the dom. So here is my hypothetical google-loader.js:
$(document).ready(function(){
$('<div id="google-loading-overlay"></div>').css({
'position': 'fixed',
'top': 0,
'right': 0,
'bottom': 0,
'left': 0,
'background': 'url(/img/busy.gif) no-repeat center center',
'background-color': '#ECECEC',
'z-index': 9999
}).appendTo($('body'));
google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']});
google.setOnLoadCallback(function(){
$('#google-loading-overlay').remove();
myDrawFunc();
});
});
The idea is simple, create an overlay before calling google.load(...), preventing user from operating the current page and display a busy indicator. After the visualization apis get loaded, remove the overlay and draw the charts.

However, it just don't work. You always get a blank page, in Chrome, it shows an null error, in firefox it looks like the loading process never end. So what's going on here? I suddenly see the light when reading this thread: The problem that you're having here is that google.setOnLoadCallback and $(document).ready are essentially synonymous.. setOnLoadCallback basically means your dom construction is finished. So the solution is very simple, just put the following line in my google-loader.js:
google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']});

1 comment:

Eric Snyder said...

Thanks! You just saved me a lot of time and frustration.