注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