我使用的是d3 word云服务,它要求在加载之前加载d3,以便正确加载。因此,在我的services.js页面中,我在word云服务之前加载d3。
这在大多数情况下是可行的。但是,偶尔会出现这样的情况,即“云”一词无法正确加载,我会得到错误:
未定义(localhost:8080/lib/d3-word-cloud.js:400)的未定义的ReferenceError: d3
这是因为服务没有按正确的顺序加载吗?我能做些什么来纠正这个问题?
编辑:代码如下:
myApp.factory('d3Service', ['$document', '$window', '$q', '$rootScope',
function ($document, $window, $q, $rootScope) {
var d = $q.defer(),
d3service = {
d3: function() { return d.promise; }
};
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { d.resolve($window.d3); });
}
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = 'http://d3js.org/d3.v3.min.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
}
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return d3service;
}]);
myApp.factory('d3Cloud', ['$document', '$window', '$q', '$rootScope',
function ($document, $window, $q, $rootScope) {
var d = $q.defer(),
d3cloud = {
cloud: function() { return d.promise; }
};
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { d.resolve($window.d3); });
}
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = '../lib/d3-word-cloud.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
}
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return d3cloud;
}]);发布于 2015-04-25 10:21:17
不确定为什么会这样,但解决方法可能是在使用typeof d3之前检查它(如果没有,则等待或重新加载它)。
如果是网页,为什么不在d3上加载<script>并使用就绪/加载方法而不是动态地进行呢?
发布于 2015-06-16 18:08:56
因此,我想您想在应用程序启动时执行以下操作:
angular.module('d3CloudApp', [])
.run(['d3Service', 'd3Cloud', function(d3Service, d3Cloud){
d3Service.d3()
.then(function(d3){
d3Cloud.cloud();
})
})]
应该有效:-)说过在d3Cloud中的第二个解决方案可能是错误的:
d.resolve($window.d3);
应该是这样的:
d.resolve($window.d3Word);
https://stackoverflow.com/questions/24195739
复制相似问题