google.load causes empty dom/screen

久未见 提交于 2019-12-22 02:51:19

问题


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);
}

});

回答1:


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.




回答2:


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




回答3:


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";


来源:https://stackoverflow.com/questions/5300550/google-load-causes-empty-dom-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!