长话短说:有一个上传文件元素和一个带有onclick函数的按钮,名为" start"。因此,所有这些都在加载所有DOM内容后发生。
createLoader: function(){
var outerDiv = document.createElement('div');
var innerDiv = document.createElement('div');
innerDiv.className = '_gisplayloader';
var mapDiv = this.getContainer();
/*outerDiv.style = ' opacity: 0.5; background-color: grey; justify-content: center; display: flex;';
outerDiv.style.position = 'absolute';
outerDiv.style.zIndex = '999999999';*/
outerDiv.className = '_gisplayLoaderOuterDiv';
outerDiv.style.height = mapDiv.offsetHeight;
outerDiv.style.width = mapDiv.offsetWidth;
outerDiv.appendChild(innerDiv);
this.loaderDiv = outerDiv;
mapDiv.parentElement.insertBefore(outerDiv, mapDiv);
}
这是loader / spinner创建和追加代码。如果我通过浏览器控制台调用它,它会立即生效。
在start()内部,它读取上传的文件,而onloadend调用另一个调用createLoader()的函数。
function start(){
//var data = new Array();
var time = Date.now();
console.log("starting...");
var reader = new FileReader();
reader.onloadend = function(){
var data = JSON.parse(reader.result);
var datareadtimestamp = Date.now();
makeChoropleth(map, data ,options,null);
}
reader.readAsText(document.getElementById("file").files[0]);
}
makeChoropleth函数的简化版本:
makeChoropleth: function(bgmap, geometry, options,defaultid){
var gismap = new Choropleth(bgmap, geometry, options); //inside here it calls createLoader()
//the next 3 functions take about 5-10s to execute all together
gismap.processData(geometry);
gismap.draw();
gismap.buildLegend();
if(options.loader != false){
// gismap.loader(); that would hide the loader. disabled it so i could check if the loader was appearing at all
}
}
除非我在makeChoropleth中的某处放置断点,否则加载器仅显示所有代码完成。以下代码需要大约10秒钟才能完成,这足以创建加载器(假设它是异步的)。为什么会这样?怎么能解决它?
答案 0 :(得分:0)
如果您希望在文件完成阅读之前显示加载程序,则需要在onloadend
函数之前的start()
函数中调用它。
function start(){
//var data = new Array();
var time = Date.now();
console.log("starting...");
var reader = new FileReader();
reader.onloadend = function(){
//stuff here only runs after the file is read completely!
var data = JSON.parse(reader.result);
var datareadtimestamp = Date.now();
makeChoropleth(map, data ,options,null);
}
reader.readAsText(document.getElementById("file").files[0]);
createLoader();
}
如果您希望在文件读取完成之后但在Choropleth代码运行之前显示加载程序,最简单的方法是在5-10s操作上设置1ms超时,以便浏览器有时间进行重排。 (否则阻塞代码将首先运行)。尝试:
makeChoropleth: function(bgmap, geometry, options,defaultid){
var gismap = new Choropleth(bgmap, geometry, options); //inside here it calls createLoader()
//the next 3 functions take about 5-10s to execute all together
setTimeout(function(){
gismap.processData(geometry);
gismap.draw();
gismap.buildLegend();
},1);
if(options.loader != false){
// gismap.loader(); that would hide the loader. disabled it so i could check if the loader was appearing at all
}
}