我有运行返回的json数据的此功能。在chrome中速度确实很高,但是在IE和FF中却很慢。有关如何改善此问题的建议?返回的数据约为15个对象。这将在顶部创建一堆锚点,并在每个标题下列出。
function list_response(jsonData) { "use strict"; var lists = document.getElementById("lists"), anchors = document.getElementById("anchors"), jItems = jsonData.items; jItems.sort(function (a, b) { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); for (var i = 0; i < jItems.length; i++) { var pList = jItems[i], str = "", ank = ""; str += '<span class="backtotop">[ <a href="#">Back to top</a> ]</span><br /><br /><br /><li class="title nodot"><a class="pHeader" name="' + pList.name + '"><h2>' + pList.name + '</h2></a></li>'; ank += '<a class="pHeader" href="#' + pList.name + '">' + pList.name + '</a> '; lists.innerHTML += str; anchors.innerHTML += ank; for (var j = 0; j < jsonData.items[i]["videos"].length; j++) { var vList = jsonData.items[i]["videos"][j]; var strs = ""; strs += '<li class="nodot"><a href="https://www.site.org/videos/Video_Player.page?bctid=' + vList.id + '">' + vList.name + '</a></li>'; lists.innerHTML += strs; } } }
这是结合以下性能增强功能的代码版本:
jItems.length
20
.push()
.join()
pList
pList.name
jItems[i]
for
jItems[i]["videos"]
jsonData.items
这些更改产生以下代码:
function list_response(jsonData) { "use strict"; var lists = document.getElementById("lists"), anchors = document.getElementById("anchors"), jItems = jsonData.items; var results = [], anks = [], vList, pListName, item, videoItem; // precache all lower case versions to make sorting faster var i, iLen = jItems.length, j, jLen; for (var i = 0; i < iLen; i++) { jItems[i].nameLower = jItems[i].name.toLowerCase(); } jItems.sort(function (a, b) { return a.nameLower.localeCompare(b.nameLower); }); for (i = 0; i < iLen; i++) { item = jItems[i]; // cache for use in loops videoItem = item["videos"]; // cache for use in loops pListName = item.name; // cache for use in multiple places results.push('<span class="backtotop">[ <a href="#">Back to top</a> ]</span><br /><br /><br /><li class="title nodot"><a class="pHeader" name="' + pListName + '"><h2>' + pListName + '</h2></a></li>'); anks.push('<a class="pHeader" href="#' + pListName + '">' + pListName + '</a> '); for (j = 0, jLen = videoItem.length; j < jLen; j++) { vList = videoItem[j]; results.push('<li class="nodot"><a href="https://www.site.org/videos/Video_Player.page?bctid=' + vList.id + '">' + vList.name + '</a></li>'); } } lists.innerHTML += results.join(""); anchors.innerHTML += anks.join(""); }