我正在使用OpenLayers为层切换器渲染DOM,大约有1200个div。问题可以简化如下。
这非常快(大约3秒钟):
var allLayers = [layerMapnik, layerCycleMap];
for(var ii = 0; ii < 1200; ++ii) {
console.log("ii = " + ii.toString());
var groupName = "wms/Transit/railroad/image/" + ii;
var layName = "CycleMap" + ii.toString();
var oneLayer = new OpenLayers.Layer.XYZ(layName, "http://whatever/tile/${z}/${y}/${x}", {visibility: false, group:groupName});
allLayers.push(oneLayer);
}
console.log("adding layers");
map.addLayers(allLayers);
$.getJSON("sampleArray.json", {}, function( doc ) {
console.log(doc.length);
});
但是一旦将for循环置于getJson回调中,它就会非常缓慢并冻结浏览器,即使for-loop根本没有读取'doc'也是如此!
var allLayers = [layerMapnik, layerCycleMap];
$.getJSON("sampleArray.json", {}, function( doc ) {
console.log(doc.length);
for(var ii = 0; ii < 1200; ++ii) {
console.log("ii = " + ii.toString());
var groupName = "wms/Transit/railroad/image/" + ii;
var layName = "CycleMap" + ii.toString();
var oneLayer = new OpenLayers.Layer.XYZ(layName, "http://whatever/tile/${z}/${y}/${x}", {visibility: false, group:groupName});
allLayers.push(oneLayer);
}
console.log("adding layers");
map.addLayers(allLayers);
});
无论json文件是多么简单sampleArray.json:
[
{
"a": 123,
"b": 456
},
{
"c": "ccc",
"d": "ddd"
}
]
我是否使用了getJSON或回调错误?或者它是一个OpenLayer的东西?
我也试过$ .each而不是for-loop,没有帮助。
答案 0 :(得分:0)
回答我自己的问题,以备将来参考。
添加LayerSwitcher也应该在回调函数中。因为整个LayerSwitcher div应该在将它添加到主html之前生成,否则切换器中每个添加的图层的重绘会减慢速度并冻结浏览器。
另外,在$(document).ready()之外调用$ .ajax是有帮助的,因为数据提取不需要等待$(文档)