I have this function that runs over returned json data. It is really fast in chrome, but slow in IE and FF. Suggestions on how I might improve this? The data returned is about 15 objects. This creates a bunch of anchors at the top with lists under each heading.
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;
}
}
}
Here’s a version of your code that combines the following performance enhancements:
jItems.lengthwas20and the average number of videos was 5, this would cut the number of DOM transactions to 1/50th the number of DOM transactions..push()and do a.join()at the very end rather than adding onto the end of the string every time. The JS engine can often join lots of strings at once much more efficiently than joining each segment piecemeal.pListand then have four references topList.name, just get the name value once and use it directly.jItems[i]in the loop because it’s referenced several places rather than recalculating it every time.forloop just once and compare to that rather than recalculating it on every iteration.jItems[i]["videos"]once in the outer loop rather than redoing it every time in the inner loop.jsonData.items, then the sort algorithm isn’t very efficient since it has to recalculate a lowercase version of each name for every comparison. You could prebuild all the lowercase versions in one pass (once per item) and then just use them in the sort algorithm rather than have to redo them every time two items are compared.These changes result in this code: