脚本和内联脚本的 SetTimeOut

SetTimeOut for script and inline script

有一张来自 2gis 的地图,它首先加载外部脚本,然后在内联脚本中加载地图小部件(如果我理解正确的话)。仅在加载主脚本后才需要延迟加载脚本和运行 内联脚本。

<script src="https://widgets.2gis.com/js/DGWidgetLoader.js"></script>

<script>new DGWidgetLoader({"width":640,"height":600,"borderColor":"#a3a3a3","pos":{"lat":52.291708811505536,"lon":104.33831691741945,"zoom":16},"opt":{"city":"irkutsk"},"org":[{"id":"1548640653330917"}]});</script>

我已经尝试了不同的选项,包括下面的选项,但是结束 </script> 标记时出现错误。

window.addEventListener('load', function() {
  setTimeout(function() {
    elem = document.createElement('script');
    elem.src = 'https://widgets.2gis.com/js/DGWidgetLoader.js';
    elem.onload = function() {
      document.dispatchEvent(new CustomEvent('scroll'))
    }
    document.body.appendChild(elem);
  }, 2000);
}, false);

window.addEventListener('load', function() {
  setTimeout(function() {
    jQuery("#2gismaps").append('<script>new DGWidgetLoader({"width":640,"height":600,"borderColor":"#a3a3a3","pos":{"lat":52.291708811505536,"lon":104.33831691741945,"zoom":16},"opt":{"city":"irkutsk"},"org":[{"id":"1548640653330917"}]});</script>');
  }, 3000);
}, false);
<div id="2gismaps" style="width: 100%; height: 420px;"></div>

你不用输出JavaScript中的HTML到运行吧。加载脚本后,您可以在 onload 处理程序中 运行 您的 JavaScript。 onload 方法使您可以控制在加载完成后执行某些操作。

window.addEventListener('load', function() {
  let script = document.createElement('script');
  script.src = 'https://widgets.2gis.com/js/DGWidgetLoader.js';
  script.onload = function() {
    // The script has now loaded, so you can call the DGWidgetLoader loader.
    new DGWidgetLoader({
      "width":640,
      "height":600,
      "borderColor":"#a3a3a3",
      "pos": {
        "lat":52.291708811505536,
        "lon":104.33831691741945,
        "zoom":16
      },
      "opt": {
        "city":"irkutsk"
      },
      "org": [
        {
          "id":"1548640653330917"
        }
      ]
    });
  }
  document.body.appendChild(script);
}, false);