通过带有 meteorjs 的外部 cdn 包含外部 cesiumjs 库的正确方法是什么?

What is the right way to include an external cesiumjs library via external cdn with meteorjs?

我正在使用meteorjs,我想使用cesiumjs。我的代码如下:

在我的启动 js 文件中的客户端代码中:

Meteor.startup(function() {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');  // optional
  script.setAttribute('src', 'http://cesiumjs.org/releases/1.18/Build/Cesium/Cesium.js');
  document.getElementsByTagName('head')[0].appendChild(script);
});

在我的模板中,我为 "cesiumContainer" 添加了 div,并且在 mytemplate.js:

Template.mytemplate.rendered = function() {
    var viewer = new Cesium.Viewer('cesiumContainer');
};

我得到的错误是:

Exception from Tracker afterFlush function:
debug.js:41 ReferenceError: Cesium is not defined
    at Template.mytemplate.rendered (mytemplate.js:4)

对于我的 CSS,我只是将其包含在 "client" 目录中的 index.html 页面中的 "head" 标记中(这样做不对吗?) :

  <style>
    @import url(http://cesiumjs.org/releases/1.18/Build/Cesium/Widgets/widgets.css);
    #cesiumContainer {
      width: 100%; height: 300px; margin: 0; padding: 0; overflow: hidden;
    }
  </style>

如何将这个外部库正确地包含到我的 meteorjs 应用程序中?另外,如果我有一个显示在同一页面上的 mytemplate2(我使用的是 FlowLayout),我该如何正确访问 "viewer" 变量?是否习惯将其设置为 "global" VIEWER 变量?

我不是流星专家,但我要指出您的脚本加载是异步的。在尝试访问 Cesium 之前,您需要等待 onload 事件被您添加的 script 标记触发。另外,使用 document.head 而不是查找标签。

我希望您发布的样式内容能够正常工作。如果您更熟悉的话,您也可以使用经典 link rel="stylesheet"

var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://cesiumjs.org/releases/1.18/Build/Cesium/Cesium.js');
document.head.appendChild(script);

script.onload = function() {
  document.getElementById('msg').innerHTML = 'Cesium version: ' + Cesium.VERSION;
}

// Cesium is undefined here.  Call your code from the onload handler above.
<p id="msg">Loading...</p>