2016-02-16 18 views
1

我正在使用meteorjs,我想使用cesiumjs。我的代碼如下:通過外部cdn與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」的股利,並有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,我只是將其包含在中「客戶」目錄內dex.html頁中的「頭」的標籤(這是不正確的嗎?):

<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變量?

回答

0

我不是流星專家,但我會指出你的腳本加載是異步的。在嘗試訪問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>