Search code examples
javascriptmeteorcesiumjs

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


I am using meteorjs, I want to use cesiumjs. My code is as follows:

In my client code in my startup js file:

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

In a template I have, I include the div for the "cesiumContainer", and have inside of mytemplate.js:

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

The error I am getting is:

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

For my CSS, I just include it in the index.html page within the "client" directory in the "head" tag (is this not right to do?):

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

How do I properly include this external library into my meteorjs application? Also, if I have a mytemplate2 that shows up on the same page (I am using FlowLayout), how do I properly get access to the "viewer" variable? Is it customary to just set it to a "global" VIEWER variable?


Solution

  • I'm no meteor expert, but I'll point out that your script load is asynchronous. You need to wait for the onload event to be fired by the script tag that you added, before you attempt to access Cesium. Also, use document.head instead of looking up the tag.

    I expect the style stuff you posted will work fine. You can also use the classic link rel="stylesheet" if that's more familiar.

    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>