为什么 google.load 会导致我的页面变成空白?

这看起来很奇怪,但我找不到解决办法。

为什么在世界上这个小提琴 http://jsfiddle.net/carlesso/PKkFf/显示页面内容,然后,当 google.load 发生时,页面变成空白?

如果 google.load 立即完成,那么它会工作得很好,但是延迟它根本不会工作。

这里是你的懒人(或者更聪明的人)的页面源代码:

<!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>​
26446 次浏览

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

Note: The following is good for avoiding a time delay - it's just in time. The example can be used generally by all scripts (needing it), but was particularly used with Greasemonkey. It also uses the Google chart API as an example, but this solution goes beyond to other Google APIs and can be used anywhere you need to wait for a script to load.

Using google.load with a callback did not solve the issue when using Greasemonkey to add a Google chart. In the process (Greasemonkey injected into page), the www.google.com/jsapi script node is added. After adding this element for Google's jsapi javascript, the injected (or page) script is ready to use the the google.load command (which needs to be loaded in the added node), but this jsapi script did not load yet. Setting the a timeout worked, but the timeout was merely a workaround for the Google jsapi script load's timing race with the injected/page script. Moving around where a script executes the google.load (and possibly google.setOnLoadCallback) can affect the timing race situation. The following proffers a solution that waits for the google script element to load before calling google.load. Here is an example:

// ********* INJECTED SCRIPT *********//
// add element
var gscript = document.createElement('script');
gscript.setAttribute("type", "application/javascript");
gscript.setAttribute("id", "XX-GMPlusGoogle-XX");
document.body.appendChild(gscript);


// event listener setup
gscript.addEventListener("load",
function changeCB(params) {
gscript.removeEventListener("load", changeCB);
google.load("visualization", "1", {packages:["corechart"], "callback":
function drawChart() {
var data;
// set the durationChart data (not in example)
data = new google.visualization.arrayToDataTable(durationChart);


var options = {
title:"Chart Title",
legend: {position:"none"},
backgroundColor:"white",
colors:["white","Blue"],
width: window.innerWidth || document.body.clientWidth,
height: window.innerHeight || document.body.clientHeight,
vAxis: {title: "Durations", baselineColor: "black", textStyle:{fontSize:12}},
hAxis: {title: "Days Since First Instance"},
height: ((cnt > 5)? cnt * 50 : 300),
isStacked: true
}; // options




// put chart into your div element
var chart = new google.visualization.BarChart(document.getElementById('XX-ChartDiv-XX'));
chart.draw(data, options);
} // drawChart function
}); //packages within google.load & google load
} // callback changeCB
);


// can use SSL as "https://www.google.com/jsapi";
gscript.src = "http://www.google.com/jsapi";

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.

You don't need to set timeout. There is another way:

$.getScript("https://www.google.com/jsapi", function () {
google.load('visualization', '1', { 'callback': 'alert()', 'packages': ['corechart'] });
});

Explanation:

 function () {
google.load('visualization', '1', { 'callback': 'alert()', 'packages': ['corechart'] });
}

will be executed ​​after successful load JSAPI script, then alert() will be executed ​​after successful google.load()

I encountered this problem when attempting to move a google.load(…) inside a jQuery $(document).ready(…) wrapper. Moving the google.load(…) back outside of the ready function so it executes immediately solved the problem.

For example, this doesn't work:

$(document).ready(function() {
google.load('visualization', '1', {packages: ['corechart']});
});

But this does:

google.load('visualization', '1', {packages: ['corechart']});
$(document).ready(function() {
// …
});