注2秒钟的等待:以下为好,以避免时间延迟 - 它只是在时间。这个例子通常可以被所有的脚本使用(需要它),但特别与Greasemonkey一起使用。它还使用Google图表API作为示例,但该解决方案不仅限于其他Google API,还可以用于需要等待脚本加载的任何位置。
使用的google.load有回调并没有解决这个问题用的Greasemonkey时添加谷歌的图表。在这个过程中(Greasemonkey注入页面),添加了www.google.com/jsapi脚本节点。加入此元素为谷歌的JSAPI JavaScript之后,注入(或页面)的脚本就可以使用了的google.load命令(需要在添加的节点被加载),但这个JSAPI脚本没有加载呢。设置超时工作,但超时仅仅是Google jsapi脚本加载与注入/页面脚本的时间竞争的一种解决方法。在脚本执行google.load(也可能是google.setOnLoadCallback)的地方移动会影响计时竞赛的情况。下面介绍一个解决方案,在调用google.load之前等待google脚本元素加载。这里有一个例子:
// ********* 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";
有趣的问题,这里有一个链接:http://friendlybit.com/js/lazy-loading -asyncronous-javascript /(换句话说:还没有线索) – mindandmedia 2012-03-01 16:23:49
我注意到,那document.write('anything')也会清除以前的html,也许文档在settimeout的上下文中不合时宜? – mindandmedia 2012-03-01 16:29:21