Why does google.load cause my page to go blank?

Well, this looks strange but I'm not able to find a solution.

Why in the world does this fiddle http://jsfiddle.net/carlesso/PKkFf/ show the page content and, then when google.load occurs, the page goes blank?

It works well if the google.load is done immediately, but having it delayed does not work at all.

Here the page source for the lazier (or smarter) of you:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Ciao</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  </head>
  <body>
    <h1>Test</h1>
    <div id="quicivanno">
      <p>ciao</p>
    </div>
  </body>
  <script type="text/javascript">
       setTimeout(function() {google.load('visualization', '1.0', {'packages':['corechart']});}, 2000);
  </script>
</html>​

Solution 1:

Looks like google.load is adding the script to the page using a document.write(), which if used after the page loads, wipes out the html.

This explains more in-depth: http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/e07c2606498094e6

Using one of the ideas, you could use a callback for the load to force it use append rather than doc.write:

setTimeout(function(){google.load('visualization', '1', {'callback':'alert("2 sec wait")', 'packages':['corechart']})}, 2000);

This demonstrates the 2 second wait with the delayed alert window

Solution 2:

You just have to define a callback, and it will not clear the page (maybe the older versions of google.load() did, but apparently the new ones do not if used with callback). Here a simplified example when I'm loading the "google.charts" lib:

if(google) {
    google.load('visualization', '1.0', {
        packages: ['corechart'],
        callback: function() {
            // do stuff, if you wan't - it doesn't matter, because the page isn't blank!
        }
    } )
}

When doing it whitout callback(), I still get the blank page too - but with callback, it's fixed for me.