仅在另一个脚本完成后才运行脚本

时间:2020-02-02 13:48:37

标签: javascript jquery asynchronous promise async-await

我的HTML标头中有多个脚本。需要关注的两个问题如下:

1)JS脚本(“感染数据”)产生一个带有数据的对象。数据是从Google脚本文件中检索和计算的,因此自然要花一点时间。

2)生成地图的脚本。映射根据感染对象数据的值进行颜色编码。

问题在于地图在我可以获取对象之前就已加载,因此它不会着色。

地图应如下所示: enter image description here 地图看起来像这样: enter image description here

HTML标头:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
        <title>JQVMap - World Map</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">

        <link href="../dist/jqvmap.css" media="screen" rel="stylesheet" type="text/css"/>

        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script type="text/javascript" src="../dist/jquery.vmap.js"></script>
        <script type="text/javascript" src="../dist/maps/jquery.vmap.world.js" charset="utf-8"></script>
        <script type="text/javascript" src="js/jquery.vmap.sampledata.deaths.js"></script>
        <script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>


        <script>





          jQuery(document).ready(function () {
            jQuery('#vmap').vectorMap({
              map: 'world_en',
              backgroundColor: '#333333',
              color: '#ffffff',
              hoverOpacity: 0.8,
              selectedColor: '#3498DB',
              enableZoom: true,
              showTooltip: true,
              scaleColors: ['#F3A291', '#FF4F3B'],
              values: infected_data,
              normalizeFunction: 'polynomial',
              onLabelShow: function(event, label, code)
        {
          // Remove for Russian Joke
            /*if (code == 'ru')
            {
                // Plain TEXT labels
                label.text('Bears, vodka, balalaika');
            }

            else*/


                label.html('<div class="map-tooltip"><h1 class="header">'+label.html()+'</h1><p class="description">Infected: '+infected_data[code]+'</p><p class="description">Deaths: '+death_data[code]+'</p></div>');


            /*else if (code == 'us')
            {

                label.html(label.html()+' (GDP - '+sample_data[code]+')');
            }*/
        },
        /*onRegionOver: function(event, code)
        {
            if (code == 'ca')
            {
                event.preventDefault();
            }
        },            */
            });
          });
        </script>







</head>

受感染的数据JS文件:

    var infected_dataINT = {};
var infected_data = {};
  const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";

  // Declare an async function
  const getData = async () => {
  // Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled 
  // When the variable is fetched, use the .then() callback to carry on 
    const DataJSON = await fetch(url).then(response => 
      response.json()
    )

    return await DataJSON
  };



  console.log(getData());

  getData().then(result => {
    console.log(result);
    infected_dataINT = result;
    console.log(infected_dataINT);

    function toString(o) {
      Object.keys(o).forEach(k => {
        if (typeof o[k] === 'object') {
          return toString(o[k]);
        }

        o[k] = '' + o[k];
      });

      return o;
    }

    console.log(toString(infected_dataINT));
    infected_data = toString(infected_dataINT);

  })

如何jQuery(document).ready(function () {....运行后才放慢<script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>的运行速度

3 个答案:

答案 0 :(得分:2)

从服务器收到响应后,您可以将script元素动态地追加到文档中,如下所示:

let script = document.createElement('script');
script.src = 'myJqueryFile.js';
document.head.appendChild(script);

您只需要将这些jquery代码放入.js文件中即可。

答案 1 :(得分:0)

听起来像是紧急问题...

您在哪里关闭标题?

</head>

您的onload事件在哪里同步呢?

<body onload="Function_That_KickStarts_Everything();">

答案 2 :(得分:0)

请使用正确的文档结构,并确保所有内容均以ONLOAD事件开头,以便第三方库都可以加载和同步...请遵循以下步骤:

#include <stdio.h>

_Bool wildcard_strcmp(char *line, char *pattern)
{
    _Bool wildcard = 0;
    char *placeholder;

    do
    {
        if ((*pattern == *line) || (*pattern == '?'))
        {
            line++;
            pattern++;
        }
        else if (*pattern == '*')
        {
            if (*(++pattern) == '\0')
            {
                return 1;
            }
            wildcard = 1;
        }
        else if (wildcard)
        {
            if (pattern == placeholder)
            {
                line++;
            }
            else
            {
                pattern = placeholder;
            }
        } 
        else
        {
            return 0;
        }
    } while (*line);

    if (*pattern == '\0')
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    char string[200] = "foobarfoobar";
    char pattern[200] = "fo?*barfoo*";

    if (wildcard_strcmp(string, pattern))
    {
        printf("Match\n");
    }
    else
    {
        printf("No Match\n");
    }

    return 0;
}