google.load 导致 dom/screen 为空

发布于 2024-10-22 00:52:28 字数 1993 浏览 2 评论 0原文

我正在尝试异步添加谷歌可视化,但遇到了问题。我已将范围缩小到导致问题的 google.load 。当 google.load 部分 js 运行时,我得到一个空的屏幕/dom。任何人都知道我做错了什么。

我也尝试过使用 google.setOnLoadCallback,得到了相同的结果。

任何帮助都会很棒

相关代码:

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


                function drawVisualization() {
                   $.ajax({
                        type: "POST",
                        data: "{'monitorId':'" + monitor + "','monitorName':'" + name + "','context':'" + context + "'}",
                        dataType: "json",
                        url: "WebService.asmx/LoadMonitorToolGeo",
                        contentType: "application/json; charset=utf-8",
                        processData: true,
                        success: function (msg) {

                            var obj = jQuery.parseJSON(msg.d);


                            // $(msg.d).hide().appendTo("#sortable").fadeIn();
                            $("#" + obj.context).find(".toolContent").hide().html(obj.data).fadeIn();

                            DrawWorldMap(obj.map, obj.context);

                        },
                        error: function (req, status, error) {

                        },
                        complete: function (req, status) {


                        }
                    });



function DrawWorldMap(response, id) {
    var data = new google.visualization.DataTable();
    data.addRows(response.d.length);
    data.addColumn('string', 'Country');
    data.addColumn('number', 'Popularity');
    for (var i = 0; i < response.d.length; i++) {
        data.setValue(i, 0, response.d[i].Country);
        data.setValue(i, 1, response.d[i].Popularity);
    }
    var options = {};
    options['dataMode'] = 'regions';

    var container = document.getElementById(id);
    var geomap = new google.visualization.GeoMap(container);
    geomap.draw(data, options);
}

});

I'm trying to add a google visualization asynchronous, but I am running into problems. I've narrowed it down to the google.load causing the problem. When google.load part of the js runs, I get an empty screen/dom. Any one know what I am doing wrong.

I've also tried using the google.setOnLoadCallback, I get the same result.

Any help would be great

Relevant code :

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


                function drawVisualization() {
                   $.ajax({
                        type: "POST",
                        data: "{'monitorId':'" + monitor + "','monitorName':'" + name + "','context':'" + context + "'}",
                        dataType: "json",
                        url: "WebService.asmx/LoadMonitorToolGeo",
                        contentType: "application/json; charset=utf-8",
                        processData: true,
                        success: function (msg) {

                            var obj = jQuery.parseJSON(msg.d);


                            // $(msg.d).hide().appendTo("#sortable").fadeIn();
                            $("#" + obj.context).find(".toolContent").hide().html(obj.data).fadeIn();

                            DrawWorldMap(obj.map, obj.context);

                        },
                        error: function (req, status, error) {

                        },
                        complete: function (req, status) {


                        }
                    });



function DrawWorldMap(response, id) {
    var data = new google.visualization.DataTable();
    data.addRows(response.d.length);
    data.addColumn('string', 'Country');
    data.addColumn('number', 'Popularity');
    for (var i = 0; i < response.d.length; i++) {
        data.setValue(i, 0, response.d[i].Country);
        data.setValue(i, 1, response.d[i].Popularity);
    }
    var options = {};
    options['dataMode'] = 'regions';

    var container = document.getElementById(id);
    var geomap = new google.visualization.GeoMap(container);
    geomap.draw(data, options);
}

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

赏烟花じ飞满天 2024-10-29 00:52:28

本文对我有帮助:

如何动态加载 Google Maps javascript API(按需加载)

这里的区别在于在 load 中定义 callback code> method options 属性:

var options = {packages: ['corechart'], callback : myCallback};
google.load('visualization', '1', options);

我相信这样 google.setOnLoadCallback(myCallback) 将不再需要,幸运的是,当添加 callback 时,该方法似乎将不再需要清理页面。

This article helped me:

How to dynamically load the Google Maps javascript API (On demand loading)

What made the difference here was to define the callback in the load method options attribute:

var options = {packages: ['corechart'], callback : myCallback};
google.load('visualization', '1', options);

I believe this way google.setOnLoadCallback(myCallback) won't be needed anymore and fortunately, it seems when callback is added the method won't cleanup the page.

情深如许 2024-10-29 00:52:28

我有同样的问题。虽然我的可以在 Chrome 中运行,但在 Firefox 中却无法运行。

我必须添加这个才能让它工作,

setTimeout(function() {
    // Google Visualization stuff goes here
}, 0);

请参阅此处 https://nealpoole.com/blog/2010/07/jquery-getjson-firefox-and-google-visualization-madness/

另外,您可能想尝试将

google.load('visualization', '1', { 'packages': ['geomap'] }, { 'callback': drawVisualization });

html 的标头放入脚本标签并将其从 $(document).ready 函数中删除

I had the same issue. Although mine worked in chrome, it just didn't work in Firefox.

I had to add this to get it to work

setTimeout(function() {
    // Google Visualization stuff goes here
}, 0);

see here https://nealpoole.com/blog/2010/07/jquery-getjson-firefox-and-google-visualization-madness/

Also, you might want to try and put

google.load('visualization', '1', { 'packages': ['geomap'] }, { 'callback': drawVisualization });

in the header of your html in a script tag and removing it from the $(document).ready function

怀念你的温柔 2024-10-29 00:52:28

注意:以下内容适用于所有 javascript,但是使用 Greasemonkey 完成的。它还使用 Google 图表 API 作为示例,但该解决方案超越了其他 Google API,可以在任何需要等待脚本加载而无需计时器设置延迟的地方使用。

使用带有回调的 google.load 并不能解决使用 Greasemonkey 添加 Google 图表时的问题。在此过程中(Greasemonkey注入页面),添加了www.google.com/jsapi脚本节点。为 Google 的 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;
                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";

Note: The following is good for all javascript, but was done 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 WITHOUT delays set by timers.

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;
                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";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文